3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2017 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2017-05-16T22:31:39Z
16 * Namespace for all classes, static methods and static properties.
48 * Constants for MouseEvent.which
52 OO
.ui
.MouseButtons
= {
65 * Generate a unique ID for element
69 OO
.ui
.generateElementId = function () {
71 return 'oojsui-' + OO
.ui
.elementId
;
75 * Check if an element is focusable.
76 * Inspired by :focusable in jQueryUI v1.11.4 - 2015-04-14
78 * @param {jQuery} $element Element to test
79 * @return {boolean} Element is focusable
81 OO
.ui
.isFocusableElement = function ( $element
) {
83 element
= $element
[ 0 ];
85 // Anything disabled is not focusable
86 if ( element
.disabled
) {
90 // Check if the element is visible
92 // This is quicker than calling $element.is( ':visible' )
93 $.expr
.pseudos
.visible( element
) &&
94 // Check that all parents are visible
95 !$element
.parents().addBack().filter( function () {
96 return $.css( this, 'visibility' ) === 'hidden';
102 // Check if the element is ContentEditable, which is the string 'true'
103 if ( element
.contentEditable
=== 'true' ) {
107 // Anything with a non-negative numeric tabIndex is focusable.
108 // Use .prop to avoid browser bugs
109 if ( $element
.prop( 'tabIndex' ) >= 0 ) {
113 // Some element types are naturally focusable
114 // (indexOf is much faster than regex in Chrome and about the
115 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
116 nodeName
= element
.nodeName
.toLowerCase();
117 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName
) !== -1 ) {
121 // Links and areas are focusable if they have an href
122 if ( ( nodeName
=== 'a' || nodeName
=== 'area' ) && $element
.attr( 'href' ) !== undefined ) {
130 * Find a focusable child
132 * @param {jQuery} $container Container to search in
133 * @param {boolean} [backwards] Search backwards
134 * @return {jQuery} Focusable child, or an empty jQuery object if none found
136 OO
.ui
.findFocusable = function ( $container
, backwards
) {
137 var $focusable
= $( [] ),
138 // $focusableCandidates is a superset of things that
139 // could get matched by isFocusableElement
140 $focusableCandidates
= $container
141 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
144 $focusableCandidates
= Array
.prototype.reverse
.call( $focusableCandidates
);
147 $focusableCandidates
.each( function () {
148 var $this = $( this );
149 if ( OO
.ui
.isFocusableElement( $this ) ) {
158 * Get the user's language and any fallback languages.
160 * These language codes are used to localize user interface elements in the user's language.
162 * In environments that provide a localization system, this function should be overridden to
163 * return the user's language(s). The default implementation returns English (en) only.
165 * @return {string[]} Language codes, in descending order of priority
167 OO
.ui
.getUserLanguages = function () {
172 * Get a value in an object keyed by language code.
174 * @param {Object.<string,Mixed>} obj Object keyed by language code
175 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
176 * @param {string} [fallback] Fallback code, used if no matching language can be found
177 * @return {Mixed} Local value
179 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
182 // Requested language
186 // Known user language
187 langs
= OO
.ui
.getUserLanguages();
188 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
195 if ( obj
[ fallback
] ) {
196 return obj
[ fallback
];
198 // First existing language
199 for ( lang
in obj
) {
207 * Check if a node is contained within another node
209 * Similar to jQuery#contains except a list of containers can be supplied
210 * and a boolean argument allows you to include the container in the match list
212 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
213 * @param {HTMLElement} contained Node to find
214 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
215 * @return {boolean} The node is in the list of target nodes
217 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
219 if ( !Array
.isArray( containers
) ) {
220 containers
= [ containers
];
222 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
223 if ( ( matchContainers
&& contained
=== containers
[ i
] ) || $.contains( containers
[ i
], contained
) ) {
231 * Return a function, that, as long as it continues to be invoked, will not
232 * be triggered. The function will be called after it stops being called for
233 * N milliseconds. If `immediate` is passed, trigger the function on the
234 * leading edge, instead of the trailing.
236 * Ported from: http://underscorejs.org/underscore.js
238 * @param {Function} func Function to debounce
239 * @param {number} [wait=0] Wait period in milliseconds
240 * @param {boolean} [immediate] Trigger on leading edge
241 * @return {Function} Debounced function
243 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
248 later = function () {
251 func
.apply( context
, args
);
254 if ( immediate
&& !timeout
) {
255 func
.apply( context
, args
);
257 if ( !timeout
|| wait
) {
258 clearTimeout( timeout
);
259 timeout
= setTimeout( later
, wait
);
265 * Puts a console warning with provided message.
267 * @param {string} message Message
269 OO
.ui
.warnDeprecation = function ( message
) {
270 if ( OO
.getProp( window
, 'console', 'warn' ) !== undefined ) {
271 // eslint-disable-next-line no-console
272 console
.warn( message
);
277 * Returns a function, that, when invoked, will only be triggered at most once
278 * during a given window of time. If called again during that window, it will
279 * wait until the window ends and then trigger itself again.
281 * As it's not knowable to the caller whether the function will actually run
282 * when the wrapper is called, return values from the function are entirely
285 * @param {Function} func Function to throttle
286 * @param {number} wait Throttle window length, in milliseconds
287 * @return {Function} Throttled function
289 OO
.ui
.throttle = function ( func
, wait
) {
290 var context
, args
, timeout
,
294 previous
= OO
.ui
.now();
295 func
.apply( context
, args
);
298 // Check how long it's been since the last time the function was
299 // called, and whether it's more or less than the requested throttle
300 // period. If it's less, run the function immediately. If it's more,
301 // set a timeout for the remaining time -- but don't replace an
302 // existing timeout, since that'd indefinitely prolong the wait.
303 var remaining
= wait
- ( OO
.ui
.now() - previous
);
306 if ( remaining
<= 0 ) {
307 // Note: unless wait was ridiculously large, this means we'll
308 // automatically run the first time the function was called in a
309 // given period. (If you provide a wait period larger than the
310 // current Unix timestamp, you *deserve* unexpected behavior.)
311 clearTimeout( timeout
);
313 } else if ( !timeout
) {
314 timeout
= setTimeout( run
, remaining
);
320 * A (possibly faster) way to get the current timestamp as an integer
322 * @return {number} Current timestamp, in milliseconds since the Unix epoch
324 OO
.ui
.now
= Date
.now
|| function () {
325 return new Date().getTime();
329 * Reconstitute a JavaScript object corresponding to a widget created by
330 * the PHP implementation.
332 * This is an alias for `OO.ui.Element.static.infuse()`.
334 * @param {string|HTMLElement|jQuery} idOrNode
335 * A DOM id (if a string) or node for the widget to infuse.
336 * @return {OO.ui.Element}
337 * The `OO.ui.Element` corresponding to this (infusable) document node.
339 OO
.ui
.infuse = function ( idOrNode
) {
340 return OO
.ui
.Element
.static.infuse( idOrNode
);
345 * Message store for the default implementation of OO.ui.msg
347 * Environments that provide a localization system should not use this, but should override
348 * OO.ui.msg altogether.
353 // Tool tip for a button that moves items in a list down one place
354 'ooui-outline-control-move-down': 'Move item down',
355 // Tool tip for a button that moves items in a list up one place
356 'ooui-outline-control-move-up': 'Move item up',
357 // Tool tip for a button that removes items from a list
358 'ooui-outline-control-remove': 'Remove item',
359 // Label for the toolbar group that contains a list of all other available tools
360 'ooui-toolbar-more': 'More',
361 // Label for the fake tool that expands the full list of tools in a toolbar group
362 'ooui-toolgroup-expand': 'More',
363 // Label for the fake tool that collapses the full list of tools in a toolbar group
364 'ooui-toolgroup-collapse': 'Fewer',
365 // Default label for the accept button of a confirmation dialog
366 'ooui-dialog-message-accept': 'OK',
367 // Default label for the reject button of a confirmation dialog
368 'ooui-dialog-message-reject': 'Cancel',
369 // Title for process dialog error description
370 'ooui-dialog-process-error': 'Something went wrong',
371 // Label for process dialog dismiss error button, visible when describing errors
372 'ooui-dialog-process-dismiss': 'Dismiss',
373 // Label for process dialog retry action button, visible when describing only recoverable errors
374 'ooui-dialog-process-retry': 'Try again',
375 // Label for process dialog retry action button, visible when describing only warnings
376 'ooui-dialog-process-continue': 'Continue',
377 // Label for the file selection widget's select file button
378 'ooui-selectfile-button-select': 'Select a file',
379 // Label for the file selection widget if file selection is not supported
380 'ooui-selectfile-not-supported': 'File selection is not supported',
381 // Label for the file selection widget when no file is currently selected
382 'ooui-selectfile-placeholder': 'No file is selected',
383 // Label for the file selection widget's drop target
384 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
388 * Get a localized message.
390 * After the message key, message parameters may optionally be passed. In the default implementation,
391 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
392 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
393 * they support unnamed, ordered message parameters.
395 * In environments that provide a localization system, this function should be overridden to
396 * return the message translated in the user's language. The default implementation always returns
397 * English messages. An example of doing this with [jQuery.i18n](https://github.com/wikimedia/jquery.i18n)
401 * var i, iLen, button,
402 * messagePath = 'oojs-ui/dist/i18n/',
403 * languages = [ $.i18n().locale, 'ur', 'en' ],
406 * for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
407 * languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
410 * $.i18n().load( languageMap ).done( function() {
411 * // Replace the built-in `msg` only once we've loaded the internationalization.
412 * // OOjs UI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
413 * // you put off creating any widgets until this promise is complete, no English
414 * // will be displayed.
415 * OO.ui.msg = $.i18n;
417 * // A button displaying "OK" in the default locale
418 * button = new OO.ui.ButtonWidget( {
419 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
422 * $( 'body' ).append( button.$element );
424 * // A button displaying "OK" in Urdu
425 * $.i18n().locale = 'ur';
426 * button = new OO.ui.ButtonWidget( {
427 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
430 * $( 'body' ).append( button.$element );
433 * @param {string} key Message key
434 * @param {...Mixed} [params] Message parameters
435 * @return {string} Translated message with parameters substituted
437 OO
.ui
.msg = function ( key
) {
438 var message
= messages
[ key
],
439 params
= Array
.prototype.slice
.call( arguments
, 1 );
440 if ( typeof message
=== 'string' ) {
441 // Perform $1 substitution
442 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
443 var i
= parseInt( n
, 10 );
444 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
447 // Return placeholder if message not found
448 message
= '[' + key
+ ']';
455 * Package a message and arguments for deferred resolution.
457 * Use this when you are statically specifying a message and the message may not yet be present.
459 * @param {string} key Message key
460 * @param {...Mixed} [params] Message parameters
461 * @return {Function} Function that returns the resolved message when executed
463 OO
.ui
.deferMsg = function () {
464 var args
= arguments
;
466 return OO
.ui
.msg
.apply( OO
.ui
, args
);
473 * If the message is a function it will be executed, otherwise it will pass through directly.
475 * @param {Function|string} msg Deferred message, or message text
476 * @return {string} Resolved message
478 OO
.ui
.resolveMsg = function ( msg
) {
479 if ( $.isFunction( msg
) ) {
486 * @param {string} url
489 OO
.ui
.isSafeUrl = function ( url
) {
490 // Keep this function in sync with php/Tag.php
491 var i
, protocolWhitelist
;
493 function stringStartsWith( haystack
, needle
) {
494 return haystack
.substr( 0, needle
.length
) === needle
;
497 protocolWhitelist
= [
498 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
499 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
500 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
507 for ( i
= 0; i
< protocolWhitelist
.length
; i
++ ) {
508 if ( stringStartsWith( url
, protocolWhitelist
[ i
] + ':' ) ) {
513 // This matches '//' too
514 if ( stringStartsWith( url
, '/' ) || stringStartsWith( url
, './' ) ) {
517 if ( stringStartsWith( url
, '?' ) || stringStartsWith( url
, '#' ) ) {
525 * Check if the user has a 'mobile' device.
527 * For our purposes this means the user is primarily using an
528 * on-screen keyboard, touch input instead of a mouse and may
529 * have a physically small display.
531 * It is left up to implementors to decide how to compute this
532 * so the default implementation always returns false.
534 * @return {boolean} Use is on a mobile device
536 OO
.ui
.isMobile = function () {
545 * Namespace for OOjs UI mixins.
547 * Mixins are named according to the type of object they are intended to
548 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
549 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
550 * is intended to be mixed in to an instance of OO.ui.Widget.
558 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
559 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
560 * connected to them and can't be interacted with.
566 * @param {Object} [config] Configuration options
567 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
568 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
570 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
571 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
572 * @cfg {string} [text] Text to insert
573 * @cfg {Array} [content] An array of content elements to append (after #text).
574 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
575 * Instances of OO.ui.Element will have their $element appended.
576 * @cfg {jQuery} [$content] Content elements to append (after #text).
577 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
578 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
579 * Data can also be specified with the #setData method.
581 OO
.ui
.Element
= function OoUiElement( config
) {
582 // Configuration initialization
583 config
= config
|| {};
587 this.elementId
= null;
589 this.data
= config
.data
;
590 this.$element
= config
.$element
||
591 $( document
.createElement( this.getTagName() ) );
592 this.elementGroup
= null;
595 if ( Array
.isArray( config
.classes
) ) {
596 this.$element
.addClass( config
.classes
.join( ' ' ) );
599 this.setElementId( config
.id
);
602 this.$element
.text( config
.text
);
604 if ( config
.content
) {
605 // The `content` property treats plain strings as text; use an
606 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
607 // appropriate $element appended.
608 this.$element
.append( config
.content
.map( function ( v
) {
609 if ( typeof v
=== 'string' ) {
610 // Escape string so it is properly represented in HTML.
611 return document
.createTextNode( v
);
612 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
615 } else if ( v
instanceof OO
.ui
.Element
) {
621 if ( config
.$content
) {
622 // The `$content` property treats plain strings as HTML.
623 this.$element
.append( config
.$content
);
629 OO
.initClass( OO
.ui
.Element
);
631 /* Static Properties */
634 * The name of the HTML tag used by the element.
636 * The static value may be ignored if the #getTagName method is overridden.
642 OO
.ui
.Element
.static.tagName
= 'div';
647 * Reconstitute a JavaScript object corresponding to a widget created
648 * by the PHP implementation.
650 * @param {string|HTMLElement|jQuery} idOrNode
651 * A DOM id (if a string) or node for the widget to infuse.
652 * @return {OO.ui.Element}
653 * The `OO.ui.Element` corresponding to this (infusable) document node.
654 * For `Tag` objects emitted on the HTML side (used occasionally for content)
655 * the value returned is a newly-created Element wrapping around the existing
658 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
659 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, false );
660 // Verify that the type matches up.
661 // FIXME: uncomment after T89721 is fixed (see T90929)
663 if ( !( obj instanceof this['class'] ) ) {
664 throw new Error( 'Infusion type mismatch!' );
671 * Implementation helper for `infuse`; skips the type check and has an
672 * extra property so that only the top-level invocation touches the DOM.
675 * @param {string|HTMLElement|jQuery} idOrNode
676 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
677 * when the top-level widget of this infusion is inserted into DOM,
678 * replacing the original node; or false for top-level invocation.
679 * @return {OO.ui.Element}
681 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, domPromise
) {
682 // look for a cached result of a previous infusion.
683 var id
, $elem
, data
, cls
, parts
, parent
, obj
, top
, state
, infusedChildren
;
684 if ( typeof idOrNode
=== 'string' ) {
686 $elem
= $( document
.getElementById( id
) );
688 $elem
= $( idOrNode
);
689 id
= $elem
.attr( 'id' );
691 if ( !$elem
.length
) {
692 throw new Error( 'Widget not found: ' + id
);
694 if ( $elem
[ 0 ].oouiInfused
) {
695 $elem
= $elem
[ 0 ].oouiInfused
;
697 data
= $elem
.data( 'ooui-infused' );
700 if ( data
=== true ) {
701 throw new Error( 'Circular dependency! ' + id
);
704 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
705 state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
706 // restore dynamic state after the new element is re-inserted into DOM under infused parent
707 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
708 infusedChildren
= $elem
.data( 'ooui-infused-children' );
709 if ( infusedChildren
&& infusedChildren
.length
) {
710 infusedChildren
.forEach( function ( data
) {
711 var state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
712 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
718 data
= $elem
.attr( 'data-ooui' );
720 throw new Error( 'No infusion data found: ' + id
);
723 data
= JSON
.parse( data
);
727 if ( !( data
&& data
._
) ) {
728 throw new Error( 'No valid infusion data found: ' + id
);
730 if ( data
._
=== 'Tag' ) {
731 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
732 return new OO
.ui
.Element( { $element
: $elem
} );
734 parts
= data
._
.split( '.' );
735 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
736 if ( cls
=== undefined ) {
737 // The PHP output might be old and not including the "OO.ui" prefix
738 // TODO: Remove this back-compat after next major release
739 cls
= OO
.getProp
.apply( OO
, [ OO
.ui
].concat( parts
) );
740 if ( cls
=== undefined ) {
741 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
745 // Verify that we're creating an OO.ui.Element instance
748 while ( parent
!== undefined ) {
749 if ( parent
=== OO
.ui
.Element
) {
754 parent
= parent
.parent
;
757 if ( parent
!== OO
.ui
.Element
) {
758 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
761 if ( domPromise
=== false ) {
763 domPromise
= top
.promise();
765 $elem
.data( 'ooui-infused', true ); // prevent loops
766 data
.id
= id
; // implicit
767 infusedChildren
= [];
768 data
= OO
.copy( data
, null, function deserialize( value
) {
770 if ( OO
.isPlainObject( value
) ) {
772 infused
= OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, domPromise
);
773 infusedChildren
.push( infused
);
774 // Flatten the structure
775 infusedChildren
.push
.apply( infusedChildren
, infused
.$element
.data( 'ooui-infused-children' ) || [] );
776 infused
.$element
.removeData( 'ooui-infused-children' );
779 if ( value
.html
!== undefined ) {
780 return new OO
.ui
.HtmlSnippet( value
.html
);
784 // allow widgets to reuse parts of the DOM
785 data
= cls
.static.reusePreInfuseDOM( $elem
[ 0 ], data
);
786 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
787 state
= cls
.static.gatherPreInfuseState( $elem
[ 0 ], data
);
789 // eslint-disable-next-line new-cap
790 obj
= new cls( data
);
791 // now replace old DOM with this new DOM.
793 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
794 // so only mutate the DOM if we need to.
795 if ( $elem
[ 0 ] !== obj
.$element
[ 0 ] ) {
796 $elem
.replaceWith( obj
.$element
);
797 // This element is now gone from the DOM, but if anyone is holding a reference to it,
798 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
799 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
800 $elem
[ 0 ].oouiInfused
= obj
.$element
;
804 obj
.$element
.data( 'ooui-infused', obj
);
805 obj
.$element
.data( 'ooui-infused-children', infusedChildren
);
806 // set the 'data-ooui' attribute so we can identify infused widgets
807 obj
.$element
.attr( 'data-ooui', '' );
808 // restore dynamic state after the new element is inserted into DOM
809 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
814 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
816 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
817 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
818 * constructor, which will be given the enhanced config.
821 * @param {HTMLElement} node
822 * @param {Object} config
825 OO
.ui
.Element
.static.reusePreInfuseDOM = function ( node
, config
) {
830 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
831 * (and its children) that represent an Element of the same class and the given configuration,
832 * generated by the PHP implementation.
834 * This method is called just before `node` is detached from the DOM. The return value of this
835 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
836 * is inserted into DOM to replace `node`.
839 * @param {HTMLElement} node
840 * @param {Object} config
843 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
848 * Get a jQuery function within a specific document.
851 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
852 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
854 * @return {Function} Bound jQuery function
856 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
857 function wrapper( selector
) {
858 return $( selector
, wrapper
.context
);
861 wrapper
.context
= this.getDocument( context
);
864 wrapper
.$iframe
= $iframe
;
871 * Get the document of an element.
874 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
875 * @return {HTMLDocument|null} Document object
877 OO
.ui
.Element
.static.getDocument = function ( obj
) {
878 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
879 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
880 // Empty jQuery selections might have a context
887 ( obj
.nodeType
=== Node
.DOCUMENT_NODE
&& obj
) ||
892 * Get the window of an element or document.
895 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
896 * @return {Window} Window object
898 OO
.ui
.Element
.static.getWindow = function ( obj
) {
899 var doc
= this.getDocument( obj
);
900 return doc
.defaultView
;
904 * Get the direction of an element or document.
907 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
908 * @return {string} Text direction, either 'ltr' or 'rtl'
910 OO
.ui
.Element
.static.getDir = function ( obj
) {
913 if ( obj
instanceof jQuery
) {
916 isDoc
= obj
.nodeType
=== Node
.DOCUMENT_NODE
;
917 isWin
= obj
.document
!== undefined;
918 if ( isDoc
|| isWin
) {
924 return $( obj
).css( 'direction' );
928 * Get the offset between two frames.
930 * TODO: Make this function not use recursion.
933 * @param {Window} from Window of the child frame
934 * @param {Window} [to=window] Window of the parent frame
935 * @param {Object} [offset] Offset to start with, used internally
936 * @return {Object} Offset object, containing left and top properties
938 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
939 var i
, len
, frames
, frame
, rect
;
945 offset
= { top
: 0, left
: 0 };
947 if ( from.parent
=== from ) {
951 // Get iframe element
952 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
953 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
954 if ( frames
[ i
].contentWindow
=== from ) {
960 // Recursively accumulate offset values
962 rect
= frame
.getBoundingClientRect();
963 offset
.left
+= rect
.left
;
964 offset
.top
+= rect
.top
;
966 this.getFrameOffset( from.parent
, offset
);
973 * Get the offset between two elements.
975 * The two elements may be in a different frame, but in that case the frame $element is in must
976 * be contained in the frame $anchor is in.
979 * @param {jQuery} $element Element whose position to get
980 * @param {jQuery} $anchor Element to get $element's position relative to
981 * @return {Object} Translated position coordinates, containing top and left properties
983 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
984 var iframe
, iframePos
,
985 pos
= $element
.offset(),
986 anchorPos
= $anchor
.offset(),
987 elementDocument
= this.getDocument( $element
),
988 anchorDocument
= this.getDocument( $anchor
);
990 // If $element isn't in the same document as $anchor, traverse up
991 while ( elementDocument
!== anchorDocument
) {
992 iframe
= elementDocument
.defaultView
.frameElement
;
994 throw new Error( '$element frame is not contained in $anchor frame' );
996 iframePos
= $( iframe
).offset();
997 pos
.left
+= iframePos
.left
;
998 pos
.top
+= iframePos
.top
;
999 elementDocument
= iframe
.ownerDocument
;
1001 pos
.left
-= anchorPos
.left
;
1002 pos
.top
-= anchorPos
.top
;
1007 * Get element border sizes.
1010 * @param {HTMLElement} el Element to measure
1011 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1013 OO
.ui
.Element
.static.getBorders = function ( el
) {
1014 var doc
= el
.ownerDocument
,
1015 win
= doc
.defaultView
,
1016 style
= win
.getComputedStyle( el
, null ),
1018 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1019 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1020 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1021 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1032 * Get dimensions of an element or window.
1035 * @param {HTMLElement|Window} el Element to measure
1036 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1038 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1040 doc
= el
.ownerDocument
|| el
.document
,
1041 win
= doc
.defaultView
;
1043 if ( win
=== el
|| el
=== doc
.documentElement
) {
1046 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1048 top
: $win
.scrollTop(),
1049 left
: $win
.scrollLeft()
1051 scrollbar
: { right
: 0, bottom
: 0 },
1055 bottom
: $win
.innerHeight(),
1056 right
: $win
.innerWidth()
1062 borders
: this.getBorders( el
),
1064 top
: $el
.scrollTop(),
1065 left
: $el
.scrollLeft()
1068 right
: $el
.innerWidth() - el
.clientWidth
,
1069 bottom
: $el
.innerHeight() - el
.clientHeight
1071 rect
: el
.getBoundingClientRect()
1077 * Get the number of pixels that an element's content is scrolled to the left.
1079 * Adapted from <https://github.com/othree/jquery.rtl-scroll-type>.
1080 * Original code copyright 2012 Wei-Ko Kao, licensed under the MIT License.
1082 * This function smooths out browser inconsistencies (nicely described in the README at
1083 * <https://github.com/othree/jquery.rtl-scroll-type>) and produces a result consistent
1084 * with Firefox's 'scrollLeft', which seems the sanest.
1088 * @param {HTMLElement|Window} el Element to measure
1089 * @return {number} Scroll position from the left.
1090 * If the element's direction is LTR, this is a positive number between `0` (initial scroll position)
1091 * and `el.scrollWidth - el.clientWidth` (furthest possible scroll position).
1092 * If the element's direction is RTL, this is a negative number between `0` (initial scroll position)
1093 * and `-el.scrollWidth + el.clientWidth` (furthest possible scroll position).
1095 OO
.ui
.Element
.static.getScrollLeft
= ( function () {
1096 var rtlScrollType
= null;
1099 var $definer
= $( '<div dir="rtl" style="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll">A</div>' ),
1100 definer
= $definer
[ 0 ];
1102 $definer
.appendTo( 'body' );
1103 if ( definer
.scrollLeft
> 0 ) {
1105 rtlScrollType
= 'default';
1107 definer
.scrollLeft
= 1;
1108 if ( definer
.scrollLeft
=== 0 ) {
1109 // Firefox, old Opera
1110 rtlScrollType
= 'negative';
1112 // Internet Explorer, Edge
1113 rtlScrollType
= 'reverse';
1119 return function getScrollLeft( el
) {
1120 var isRoot
= el
.window
=== el
||
1121 el
=== el
.ownerDocument
.body
||
1122 el
=== el
.ownerDocument
.documentElement
,
1123 scrollLeft
= isRoot
? $( window
).scrollLeft() : el
.scrollLeft
,
1124 // All browsers use the correct scroll type ('negative') on the root, so don't
1125 // do any fixups when looking at the root element
1126 direction
= isRoot
? 'ltr' : $( el
).css( 'direction' );
1128 if ( direction
=== 'rtl' ) {
1129 if ( rtlScrollType
=== null ) {
1132 if ( rtlScrollType
=== 'reverse' ) {
1133 scrollLeft
= -scrollLeft
;
1134 } else if ( rtlScrollType
=== 'default' ) {
1135 scrollLeft
= scrollLeft
- el
.scrollWidth
+ el
.clientWidth
;
1144 * Get the root scrollable element of given element's document.
1146 * On Blink-based browsers (Chrome etc.), `document.documentElement` can't be used to get or set
1147 * the scrollTop property; instead we have to use `document.body`. Changing and testing the value
1148 * lets us use 'body' or 'documentElement' based on what is working.
1150 * https://code.google.com/p/chromium/issues/detail?id=303131
1153 * @param {HTMLElement} el Element to find root scrollable parent for
1154 * @return {HTMLElement} Scrollable parent, `document.body` or `document.documentElement`
1155 * depending on browser
1157 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1158 var scrollTop
, body
;
1160 if ( OO
.ui
.scrollableElement
=== undefined ) {
1161 body
= el
.ownerDocument
.body
;
1162 scrollTop
= body
.scrollTop
;
1165 if ( body
.scrollTop
=== 1 ) {
1166 body
.scrollTop
= scrollTop
;
1167 OO
.ui
.scrollableElement
= 'body';
1169 OO
.ui
.scrollableElement
= 'documentElement';
1173 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1177 * Get closest scrollable container.
1179 * Traverses up until either a scrollable element or the root is reached, in which case the root
1180 * scrollable element will be returned (see #getRootScrollableElement).
1183 * @param {HTMLElement} el Element to find scrollable container for
1184 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1185 * @return {HTMLElement} Closest scrollable container
1187 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1189 // Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and
1190 // 'overflow-y' have different values, so we need to check the separate properties.
1191 props
= [ 'overflow-x', 'overflow-y' ],
1192 $parent
= $( el
).parent();
1194 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1195 props
= [ 'overflow-' + dimension
];
1198 // Special case for the document root (which doesn't really have any scrollable container, since
1199 // it is the ultimate scrollable container, but this is probably saner than null or exception)
1200 if ( $( el
).is( 'html, body' ) ) {
1201 return this.getRootScrollableElement( el
);
1204 while ( $parent
.length
) {
1205 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1206 return $parent
[ 0 ];
1210 val
= $parent
.css( props
[ i
] );
1211 // We assume that elements with 'overflow' (in any direction) set to 'hidden' will never be
1212 // scrolled in that direction, but they can actually be scrolled programatically. The user can
1213 // unintentionally perform a scroll in such case even if the application doesn't scroll
1214 // programatically, e.g. when jumping to an anchor, or when using built-in find functionality.
1215 // This could cause funny issues...
1216 if ( val
=== 'auto' || val
=== 'scroll' ) {
1217 return $parent
[ 0 ];
1220 $parent
= $parent
.parent();
1222 // The element is unattached... return something mostly sane
1223 return this.getRootScrollableElement( el
);
1227 * Scroll element into view.
1230 * @param {HTMLElement} el Element to scroll into view
1231 * @param {Object} [config] Configuration options
1232 * @param {string} [config.duration='fast'] jQuery animation duration value
1233 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1234 * to scroll in both directions
1235 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1237 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1238 var position
, animations
, container
, $container
, elementDimensions
, containerDimensions
, $window
,
1239 deferred
= $.Deferred();
1241 // Configuration initialization
1242 config
= config
|| {};
1245 container
= this.getClosestScrollableContainer( el
, config
.direction
);
1246 $container
= $( container
);
1247 elementDimensions
= this.getDimensions( el
);
1248 containerDimensions
= this.getDimensions( container
);
1249 $window
= $( this.getWindow( el
) );
1251 // Compute the element's position relative to the container
1252 if ( $container
.is( 'html, body' ) ) {
1253 // If the scrollable container is the root, this is easy
1255 top
: elementDimensions
.rect
.top
,
1256 bottom
: $window
.innerHeight() - elementDimensions
.rect
.bottom
,
1257 left
: elementDimensions
.rect
.left
,
1258 right
: $window
.innerWidth() - elementDimensions
.rect
.right
1261 // Otherwise, we have to subtract el's coordinates from container's coordinates
1263 top
: elementDimensions
.rect
.top
- ( containerDimensions
.rect
.top
+ containerDimensions
.borders
.top
),
1264 bottom
: containerDimensions
.rect
.bottom
- containerDimensions
.borders
.bottom
- containerDimensions
.scrollbar
.bottom
- elementDimensions
.rect
.bottom
,
1265 left
: elementDimensions
.rect
.left
- ( containerDimensions
.rect
.left
+ containerDimensions
.borders
.left
),
1266 right
: containerDimensions
.rect
.right
- containerDimensions
.borders
.right
- containerDimensions
.scrollbar
.right
- elementDimensions
.rect
.right
1270 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1271 if ( position
.top
< 0 ) {
1272 animations
.scrollTop
= containerDimensions
.scroll
.top
+ position
.top
;
1273 } else if ( position
.top
> 0 && position
.bottom
< 0 ) {
1274 animations
.scrollTop
= containerDimensions
.scroll
.top
+ Math
.min( position
.top
, -position
.bottom
);
1277 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1278 if ( position
.left
< 0 ) {
1279 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ position
.left
;
1280 } else if ( position
.left
> 0 && position
.right
< 0 ) {
1281 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ Math
.min( position
.left
, -position
.right
);
1284 if ( !$.isEmptyObject( animations
) ) {
1285 $container
.stop( true ).animate( animations
, config
.duration
=== undefined ? 'fast' : config
.duration
);
1286 $container
.queue( function ( next
) {
1293 return deferred
.promise();
1297 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1298 * and reserve space for them, because it probably doesn't.
1300 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1301 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1302 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1303 * and then reattach (or show) them back.
1306 * @param {HTMLElement} el Element to reconsider the scrollbars on
1308 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1309 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1310 // Save scroll position
1311 scrollLeft
= el
.scrollLeft
;
1312 scrollTop
= el
.scrollTop
;
1313 // Detach all children
1314 while ( el
.firstChild
) {
1315 nodes
.push( el
.firstChild
);
1316 el
.removeChild( el
.firstChild
);
1319 void el
.offsetHeight
;
1320 // Reattach all children
1321 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1322 el
.appendChild( nodes
[ i
] );
1324 // Restore scroll position (no-op if scrollbars disappeared)
1325 el
.scrollLeft
= scrollLeft
;
1326 el
.scrollTop
= scrollTop
;
1332 * Toggle visibility of an element.
1334 * @param {boolean} [show] Make element visible, omit to toggle visibility
1338 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1339 show
= show
=== undefined ? !this.visible
: !!show
;
1341 if ( show
!== this.isVisible() ) {
1342 this.visible
= show
;
1343 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1344 this.emit( 'toggle', show
);
1351 * Check if element is visible.
1353 * @return {boolean} element is visible
1355 OO
.ui
.Element
.prototype.isVisible = function () {
1356 return this.visible
;
1362 * @return {Mixed} Element data
1364 OO
.ui
.Element
.prototype.getData = function () {
1371 * @param {Mixed} data Element data
1374 OO
.ui
.Element
.prototype.setData = function ( data
) {
1380 * Set the element has an 'id' attribute.
1382 * @param {string} id
1385 OO
.ui
.Element
.prototype.setElementId = function ( id
) {
1386 this.elementId
= id
;
1387 this.$element
.attr( 'id', id
);
1392 * Ensure that the element has an 'id' attribute, setting it to an unique value if it's missing,
1393 * and return its value.
1397 OO
.ui
.Element
.prototype.getElementId = function () {
1398 if ( this.elementId
=== null ) {
1399 this.setElementId( OO
.ui
.generateElementId() );
1401 return this.elementId
;
1405 * Check if element supports one or more methods.
1407 * @param {string|string[]} methods Method or list of methods to check
1408 * @return {boolean} All methods are supported
1410 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1414 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1415 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1416 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1421 return methods
.length
=== support
;
1425 * Update the theme-provided classes.
1427 * @localdoc This is called in element mixins and widget classes any time state changes.
1428 * Updating is debounced, minimizing overhead of changing multiple attributes and
1429 * guaranteeing that theme updates do not occur within an element's constructor
1431 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1432 OO
.ui
.theme
.queueUpdateElementClasses( this );
1436 * Get the HTML tag name.
1438 * Override this method to base the result on instance information.
1440 * @return {string} HTML tag name
1442 OO
.ui
.Element
.prototype.getTagName = function () {
1443 return this.constructor.static.tagName
;
1447 * Check if the element is attached to the DOM
1449 * @return {boolean} The element is attached to the DOM
1451 OO
.ui
.Element
.prototype.isElementAttached = function () {
1452 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1456 * Get the DOM document.
1458 * @return {HTMLDocument} Document object
1460 OO
.ui
.Element
.prototype.getElementDocument = function () {
1461 // Don't cache this in other ways either because subclasses could can change this.$element
1462 return OO
.ui
.Element
.static.getDocument( this.$element
);
1466 * Get the DOM window.
1468 * @return {Window} Window object
1470 OO
.ui
.Element
.prototype.getElementWindow = function () {
1471 return OO
.ui
.Element
.static.getWindow( this.$element
);
1475 * Get closest scrollable container.
1477 * @return {HTMLElement} Closest scrollable container
1479 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1480 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1484 * Get group element is in.
1486 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1488 OO
.ui
.Element
.prototype.getElementGroup = function () {
1489 return this.elementGroup
;
1493 * Set group element is in.
1495 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1498 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1499 this.elementGroup
= group
;
1504 * Scroll element into view.
1506 * @param {Object} [config] Configuration options
1507 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1509 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1511 !this.isElementAttached() ||
1512 !this.isVisible() ||
1513 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1515 return $.Deferred().resolve();
1517 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1521 * Restore the pre-infusion dynamic state for this widget.
1523 * This method is called after #$element has been inserted into DOM. The parameter is the return
1524 * value of #gatherPreInfuseState.
1527 * @param {Object} state
1529 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1533 * Wraps an HTML snippet for use with configuration values which default
1534 * to strings. This bypasses the default html-escaping done to string
1540 * @param {string} [content] HTML content
1542 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
1544 this.content
= content
;
1549 OO
.initClass( OO
.ui
.HtmlSnippet
);
1556 * @return {string} Unchanged HTML snippet.
1558 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
1559 return this.content
;
1563 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1564 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1565 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1566 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1567 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1571 * @extends OO.ui.Element
1572 * @mixins OO.EventEmitter
1575 * @param {Object} [config] Configuration options
1577 OO
.ui
.Layout
= function OoUiLayout( config
) {
1578 // Configuration initialization
1579 config
= config
|| {};
1581 // Parent constructor
1582 OO
.ui
.Layout
.parent
.call( this, config
);
1584 // Mixin constructors
1585 OO
.EventEmitter
.call( this );
1588 this.$element
.addClass( 'oo-ui-layout' );
1593 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1594 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1597 * Widgets are compositions of one or more OOjs UI elements that users can both view
1598 * and interact with. All widgets can be configured and modified via a standard API,
1599 * and their state can change dynamically according to a model.
1603 * @extends OO.ui.Element
1604 * @mixins OO.EventEmitter
1607 * @param {Object} [config] Configuration options
1608 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1609 * appearance reflects this state.
1611 OO
.ui
.Widget
= function OoUiWidget( config
) {
1612 // Initialize config
1613 config
= $.extend( { disabled
: false }, config
);
1615 // Parent constructor
1616 OO
.ui
.Widget
.parent
.call( this, config
);
1618 // Mixin constructors
1619 OO
.EventEmitter
.call( this );
1622 this.disabled
= null;
1623 this.wasDisabled
= null;
1626 this.$element
.addClass( 'oo-ui-widget' );
1627 this.setDisabled( !!config
.disabled
);
1632 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1633 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1640 * A 'disable' event is emitted when the disabled state of the widget changes
1641 * (i.e. on disable **and** enable).
1643 * @param {boolean} disabled Widget is disabled
1649 * A 'toggle' event is emitted when the visibility of the widget changes.
1651 * @param {boolean} visible Widget is visible
1657 * Check if the widget is disabled.
1659 * @return {boolean} Widget is disabled
1661 OO
.ui
.Widget
.prototype.isDisabled = function () {
1662 return this.disabled
;
1666 * Set the 'disabled' state of the widget.
1668 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1670 * @param {boolean} disabled Disable widget
1673 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1676 this.disabled
= !!disabled
;
1677 isDisabled
= this.isDisabled();
1678 if ( isDisabled
!== this.wasDisabled
) {
1679 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1680 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1681 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1682 this.emit( 'disable', isDisabled
);
1683 this.updateThemeClasses();
1685 this.wasDisabled
= isDisabled
;
1691 * Update the disabled state, in case of changes in parent widget.
1695 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1696 this.setDisabled( this.disabled
);
1701 * Get an ID of a labelable node which is part of this widget, if any, to be used for `<label for>`
1704 * @return {string|null} The ID of the labelable element
1706 OO
.ui
.Widget
.prototype.getInputId = function () {
1718 OO
.ui
.Theme
= function OoUiTheme() {
1719 this.elementClassesQueue
= [];
1720 this.debouncedUpdateQueuedElementClasses
= OO
.ui
.debounce( this.updateQueuedElementClasses
);
1725 OO
.initClass( OO
.ui
.Theme
);
1730 * Get a list of classes to be applied to a widget.
1732 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1733 * otherwise state transitions will not work properly.
1735 * @param {OO.ui.Element} element Element for which to get classes
1736 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1738 OO
.ui
.Theme
.prototype.getElementClasses = function () {
1739 return { on
: [], off
: [] };
1743 * Update CSS classes provided by the theme.
1745 * For elements with theme logic hooks, this should be called any time there's a state change.
1747 * @param {OO.ui.Element} element Element for which to update classes
1749 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
1750 var $elements
= $( [] ),
1751 classes
= this.getElementClasses( element
);
1753 if ( element
.$icon
) {
1754 $elements
= $elements
.add( element
.$icon
);
1756 if ( element
.$indicator
) {
1757 $elements
= $elements
.add( element
.$indicator
);
1761 .removeClass( classes
.off
.join( ' ' ) )
1762 .addClass( classes
.on
.join( ' ' ) );
1768 OO
.ui
.Theme
.prototype.updateQueuedElementClasses = function () {
1770 for ( i
= 0; i
< this.elementClassesQueue
.length
; i
++ ) {
1771 this.updateElementClasses( this.elementClassesQueue
[ i
] );
1774 this.elementClassesQueue
= [];
1778 * Queue #updateElementClasses to be called for this element.
1780 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1781 * to make them synchronous.
1783 * @param {OO.ui.Element} element Element for which to update classes
1785 OO
.ui
.Theme
.prototype.queueUpdateElementClasses = function ( element
) {
1786 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1787 // the most common case (this method is often called repeatedly for the same element).
1788 if ( this.elementClassesQueue
.lastIndexOf( element
) !== -1 ) {
1791 this.elementClassesQueue
.push( element
);
1792 this.debouncedUpdateQueuedElementClasses();
1796 * Get the transition duration in milliseconds for dialogs opening/closing
1798 * The dialog should be fully rendered this many milliseconds after the
1799 * ready process has executed.
1801 * @return {number} Transition duration in milliseconds
1803 OO
.ui
.Theme
.prototype.getDialogTransitionDuration = function () {
1808 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1809 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1810 * order in which users will navigate through the focusable elements via the "tab" key.
1813 * // TabIndexedElement is mixed into the ButtonWidget class
1814 * // to provide a tabIndex property.
1815 * var button1 = new OO.ui.ButtonWidget( {
1819 * var button2 = new OO.ui.ButtonWidget( {
1823 * var button3 = new OO.ui.ButtonWidget( {
1827 * var button4 = new OO.ui.ButtonWidget( {
1831 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1837 * @param {Object} [config] Configuration options
1838 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1839 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1840 * functionality will be applied to it instead.
1841 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1842 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1843 * to remove the element from the tab-navigation flow.
1845 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
1846 // Configuration initialization
1847 config
= $.extend( { tabIndex
: 0 }, config
);
1850 this.$tabIndexed
= null;
1851 this.tabIndex
= null;
1854 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
1857 this.setTabIndex( config
.tabIndex
);
1858 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
1863 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
1868 * Set the element that should use the tabindex functionality.
1870 * This method is used to retarget a tabindex mixin so that its functionality applies
1871 * to the specified element. If an element is currently using the functionality, the mixin’s
1872 * effect on that element is removed before the new element is set up.
1874 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1877 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
1878 var tabIndex
= this.tabIndex
;
1879 // Remove attributes from old $tabIndexed
1880 this.setTabIndex( null );
1881 // Force update of new $tabIndexed
1882 this.$tabIndexed
= $tabIndexed
;
1883 this.tabIndex
= tabIndex
;
1884 return this.updateTabIndex();
1888 * Set the value of the tabindex.
1890 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
1893 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
1894 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
1896 if ( this.tabIndex
!== tabIndex
) {
1897 this.tabIndex
= tabIndex
;
1898 this.updateTabIndex();
1905 * Update the `tabindex` attribute, in case of changes to tab index or
1911 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
1912 if ( this.$tabIndexed
) {
1913 if ( this.tabIndex
!== null ) {
1914 // Do not index over disabled elements
1915 this.$tabIndexed
.attr( {
1916 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
1917 // Support: ChromeVox and NVDA
1918 // These do not seem to inherit aria-disabled from parent elements
1919 'aria-disabled': this.isDisabled().toString()
1922 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
1929 * Handle disable events.
1932 * @param {boolean} disabled Element is disabled
1934 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
1935 this.updateTabIndex();
1939 * Get the value of the tabindex.
1941 * @return {number|null} Tabindex value
1943 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
1944 return this.tabIndex
;
1948 * Get an ID of a focusable element of this widget, if any, to be used for `<label for>` value.
1950 * If the element already has an ID then that is returned, otherwise unique ID is
1951 * generated, set on the element, and returned.
1953 * @return {string|null} The ID of the focusable element
1955 OO
.ui
.mixin
.TabIndexedElement
.prototype.getInputId = function () {
1958 if ( !this.$tabIndexed
) {
1961 if ( !this.isLabelableNode( this.$tabIndexed
) ) {
1965 id
= this.$tabIndexed
.attr( 'id' );
1966 if ( id
=== undefined ) {
1967 id
= OO
.ui
.generateElementId();
1968 this.$tabIndexed
.attr( 'id', id
);
1975 * Whether the node is 'labelable' according to the HTML spec
1976 * (i.e., whether it can be interacted with through a `<label for="…">`).
1977 * See: <https://html.spec.whatwg.org/multipage/forms.html#category-label>.
1980 * @param {jQuery} $node
1983 OO
.ui
.mixin
.TabIndexedElement
.prototype.isLabelableNode = function ( $node
) {
1985 labelableTags
= [ 'button', 'meter', 'output', 'progress', 'select', 'textarea' ],
1986 tagName
= $node
.prop( 'tagName' ).toLowerCase();
1988 if ( tagName
=== 'input' && $node
.attr( 'type' ) !== 'hidden' ) {
1991 if ( labelableTags
.indexOf( tagName
) !== -1 ) {
1998 * Focus this element.
2002 OO
.ui
.mixin
.TabIndexedElement
.prototype.focus = function () {
2003 if ( !this.isDisabled() ) {
2004 this.$tabIndexed
.focus();
2010 * Blur this element.
2014 OO
.ui
.mixin
.TabIndexedElement
.prototype.blur = function () {
2015 this.$tabIndexed
.blur();
2020 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
2021 * interface element that can be configured with access keys for accessibility.
2022 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
2024 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
2030 * @param {Object} [config] Configuration options
2031 * @cfg {jQuery} [$button] The button element created by the class.
2032 * If this configuration is omitted, the button element will use a generated `<a>`.
2033 * @cfg {boolean} [framed=true] Render the button with a frame
2035 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
2036 // Configuration initialization
2037 config
= config
|| {};
2040 this.$button
= null;
2042 this.active
= config
.active
!== undefined && config
.active
;
2043 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
2044 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
2045 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
2046 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
2047 this.onClickHandler
= this.onClick
.bind( this );
2048 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
2051 this.$element
.addClass( 'oo-ui-buttonElement' );
2052 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
2053 this.setButtonElement( config
.$button
|| $( '<a>' ) );
2058 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
2060 /* Static Properties */
2063 * Cancel mouse down events.
2065 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
2066 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
2067 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
2072 * @property {boolean}
2074 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
2079 * A 'click' event is emitted when the button element is clicked.
2087 * Set the button element.
2089 * This method is used to retarget a button mixin so that its functionality applies to
2090 * the specified button element instead of the one created by the class. If a button element
2091 * is already set, the method will remove the mixin’s effect on that element.
2093 * @param {jQuery} $button Element to use as button
2095 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
2096 if ( this.$button
) {
2098 .removeClass( 'oo-ui-buttonElement-button' )
2099 .removeAttr( 'role accesskey' )
2101 mousedown
: this.onMouseDownHandler
,
2102 keydown
: this.onKeyDownHandler
,
2103 click
: this.onClickHandler
,
2104 keypress
: this.onKeyPressHandler
2108 this.$button
= $button
2109 .addClass( 'oo-ui-buttonElement-button' )
2111 mousedown
: this.onMouseDownHandler
,
2112 keydown
: this.onKeyDownHandler
,
2113 click
: this.onClickHandler
,
2114 keypress
: this.onKeyPressHandler
2117 // Add `role="button"` on `<a>` elements, where it's needed
2118 // `toUppercase()` is added for XHTML documents
2119 if ( this.$button
.prop( 'tagName' ).toUpperCase() === 'A' ) {
2120 this.$button
.attr( 'role', 'button' );
2125 * Handles mouse down events.
2128 * @param {jQuery.Event} e Mouse down event
2130 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
2131 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2134 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2135 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2136 // reliably remove the pressed class
2137 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
2138 // Prevent change of focus unless specifically configured otherwise
2139 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
2145 * Handles mouse up events.
2148 * @param {MouseEvent} e Mouse up event
2150 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
2151 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2154 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2155 // Stop listening for mouseup, since we only needed this once
2156 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
2160 * Handles mouse click events.
2163 * @param {jQuery.Event} e Mouse click event
2166 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
2167 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
2168 if ( this.emit( 'click' ) ) {
2175 * Handles key down events.
2178 * @param {jQuery.Event} e Key down event
2180 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
2181 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2184 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2185 // Run the keyup handler no matter where the key is when the button is let go, so we can
2186 // reliably remove the pressed class
2187 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
2191 * Handles key up events.
2194 * @param {KeyboardEvent} e Key up event
2196 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
2197 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2200 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2201 // Stop listening for keyup, since we only needed this once
2202 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
2206 * Handles key press events.
2209 * @param {jQuery.Event} e Key press event
2212 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
2213 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
2214 if ( this.emit( 'click' ) ) {
2221 * Check if button has a frame.
2223 * @return {boolean} Button is framed
2225 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
2230 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
2232 * @param {boolean} [framed] Make button framed, omit to toggle
2235 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
2236 framed
= framed
=== undefined ? !this.framed
: !!framed
;
2237 if ( framed
!== this.framed
) {
2238 this.framed
= framed
;
2240 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
2241 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
2242 this.updateThemeClasses();
2249 * Set the button's active state.
2251 * The active state can be set on:
2253 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2254 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2255 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2258 * @param {boolean} value Make button active
2261 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
2262 this.active
= !!value
;
2263 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
2264 this.updateThemeClasses();
2269 * Check if the button is active
2272 * @return {boolean} The button is active
2274 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
2279 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2280 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2281 * items from the group is done through the interface the class provides.
2282 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2284 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
2287 * @mixins OO.EmitterList
2291 * @param {Object} [config] Configuration options
2292 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2293 * is omitted, the group element will use a generated `<div>`.
2295 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
2296 // Configuration initialization
2297 config
= config
|| {};
2299 // Mixin constructors
2300 OO
.EmitterList
.call( this, config
);
2306 this.setGroupElement( config
.$group
|| $( '<div>' ) );
2311 OO
.mixinClass( OO
.ui
.mixin
.GroupElement
, OO
.EmitterList
);
2318 * A change event is emitted when the set of selected items changes.
2320 * @param {OO.ui.Element[]} items Items currently in the group
2326 * Set the group element.
2328 * If an element is already set, items will be moved to the new element.
2330 * @param {jQuery} $group Element to use as group
2332 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
2335 this.$group
= $group
;
2336 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2337 this.$group
.append( this.items
[ i
].$element
);
2342 * Get an item by its data.
2344 * Only the first item with matching data will be returned. To return all matching items,
2345 * use the #getItemsFromData method.
2347 * @param {Object} data Item data to search for
2348 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2350 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
2352 hash
= OO
.getHash( data
);
2354 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2355 item
= this.items
[ i
];
2356 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2365 * Get items by their data.
2367 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
2369 * @param {Object} data Item data to search for
2370 * @return {OO.ui.Element[]} Items with equivalent data
2372 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
2374 hash
= OO
.getHash( data
),
2377 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2378 item
= this.items
[ i
];
2379 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2388 * Add items to the group.
2390 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2391 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2393 * @param {OO.ui.Element[]} items An array of items to add to the group
2394 * @param {number} [index] Index of the insertion point
2397 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
2399 OO
.EmitterList
.prototype.addItems
.call( this, items
, index
);
2401 this.emit( 'change', this.getItems() );
2408 OO
.ui
.mixin
.GroupElement
.prototype.moveItem = function ( items
, newIndex
) {
2409 // insertItemElements expects this.items to not have been modified yet, so call before the mixin
2410 this.insertItemElements( items
, newIndex
);
2413 newIndex
= OO
.EmitterList
.prototype.moveItem
.call( this, items
, newIndex
);
2421 OO
.ui
.mixin
.GroupElement
.prototype.insertItem = function ( item
, index
) {
2422 item
.setElementGroup( this );
2423 this.insertItemElements( item
, index
);
2426 index
= OO
.EmitterList
.prototype.insertItem
.call( this, item
, index
);
2432 * Insert elements into the group
2435 * @param {OO.ui.Element} itemWidget Item to insert
2436 * @param {number} index Insertion index
2438 OO
.ui
.mixin
.GroupElement
.prototype.insertItemElements = function ( itemWidget
, index
) {
2439 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
2440 this.$group
.append( itemWidget
.$element
);
2441 } else if ( index
=== 0 ) {
2442 this.$group
.prepend( itemWidget
.$element
);
2444 this.items
[ index
].$element
.before( itemWidget
.$element
);
2449 * Remove the specified items from a group.
2451 * Removed items are detached (not removed) from the DOM so that they may be reused.
2452 * To remove all items from a group, you may wish to use the #clearItems method instead.
2454 * @param {OO.ui.Element[]} items An array of items to remove
2457 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
2458 var i
, len
, item
, index
;
2460 // Remove specific items elements
2461 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2463 index
= this.items
.indexOf( item
);
2464 if ( index
!== -1 ) {
2465 item
.setElementGroup( null );
2466 item
.$element
.detach();
2471 OO
.EmitterList
.prototype.removeItems
.call( this, items
);
2473 this.emit( 'change', this.getItems() );
2478 * Clear all items from the group.
2480 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2481 * To remove only a subset of items from a group, use the #removeItems method.
2485 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
2488 // Remove all item elements
2489 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2490 this.items
[ i
].setElementGroup( null );
2491 this.items
[ i
].$element
.detach();
2495 OO
.EmitterList
.prototype.clearItems
.call( this );
2497 this.emit( 'change', this.getItems() );
2502 * IconElement is often mixed into other classes to generate an icon.
2503 * Icons are graphics, about the size of normal text. They are used to aid the user
2504 * in locating a control or to convey information in a space-efficient way. See the
2505 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
2506 * included in the library.
2508 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2514 * @param {Object} [config] Configuration options
2515 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2516 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2517 * the icon element be set to an existing icon instead of the one generated by this class, set a
2518 * value using a jQuery selection. For example:
2520 * // Use a <div> tag instead of a <span>
2522 * // Use an existing icon element instead of the one generated by the class
2523 * $icon: this.$element
2524 * // Use an icon element from a child widget
2525 * $icon: this.childwidget.$element
2526 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2527 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2528 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2529 * by the user's language.
2531 * Example of an i18n map:
2533 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2534 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
2535 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2536 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2537 * text. The icon title is displayed when users move the mouse over the icon.
2539 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
2540 // Configuration initialization
2541 config
= config
|| {};
2546 this.iconTitle
= null;
2549 this.setIcon( config
.icon
|| this.constructor.static.icon
);
2550 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
2551 this.setIconElement( config
.$icon
|| $( '<span>' ) );
2556 OO
.initClass( OO
.ui
.mixin
.IconElement
);
2558 /* Static Properties */
2561 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2562 * for i18n purposes and contains a `default` icon name and additional names keyed by
2563 * language code. The `default` name is used when no icon is keyed by the user's language.
2565 * Example of an i18n map:
2567 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2569 * Note: the static property will be overridden if the #icon configuration is used.
2573 * @property {Object|string}
2575 OO
.ui
.mixin
.IconElement
.static.icon
= null;
2578 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2579 * function that returns title text, or `null` for no title.
2581 * The static property will be overridden if the #iconTitle configuration is used.
2585 * @property {string|Function|null}
2587 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
2592 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2593 * applies to the specified icon element instead of the one created by the class. If an icon
2594 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2595 * and mixin methods will no longer affect the element.
2597 * @param {jQuery} $icon Element to use as icon
2599 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
2602 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
2603 .removeAttr( 'title' );
2607 .addClass( 'oo-ui-iconElement-icon' )
2608 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
2609 if ( this.iconTitle
!== null ) {
2610 this.$icon
.attr( 'title', this.iconTitle
);
2613 this.updateThemeClasses();
2617 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2618 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2621 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2622 * by language code, or `null` to remove the icon.
2625 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
2626 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
2627 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
2629 if ( this.icon
!== icon
) {
2631 if ( this.icon
!== null ) {
2632 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
2634 if ( icon
!== null ) {
2635 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
2641 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
2642 this.updateThemeClasses();
2648 * Set the icon title. Use `null` to remove the title.
2650 * @param {string|Function|null} iconTitle A text string used as the icon title,
2651 * a function that returns title text, or `null` for no title.
2654 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
2655 iconTitle
= typeof iconTitle
=== 'function' ||
2656 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
2657 OO
.ui
.resolveMsg( iconTitle
) : null;
2659 if ( this.iconTitle
!== iconTitle
) {
2660 this.iconTitle
= iconTitle
;
2662 if ( this.iconTitle
!== null ) {
2663 this.$icon
.attr( 'title', iconTitle
);
2665 this.$icon
.removeAttr( 'title' );
2674 * Get the symbolic name of the icon.
2676 * @return {string} Icon name
2678 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
2683 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
2685 * @return {string} Icon title text
2687 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
2688 return this.iconTitle
;
2692 * IndicatorElement is often mixed into other classes to generate an indicator.
2693 * Indicators are small graphics that are generally used in two ways:
2695 * - To draw attention to the status of an item. For example, an indicator might be
2696 * used to show that an item in a list has errors that need to be resolved.
2697 * - To clarify the function of a control that acts in an exceptional way (a button
2698 * that opens a menu instead of performing an action directly, for example).
2700 * For a list of indicators included in the library, please see the
2701 * [OOjs UI documentation on MediaWiki] [1].
2703 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2709 * @param {Object} [config] Configuration options
2710 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
2711 * configuration is omitted, the indicator element will use a generated `<span>`.
2712 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2713 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
2715 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2716 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
2717 * or a function that returns title text. The indicator title is displayed when users move
2718 * the mouse over the indicator.
2720 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
2721 // Configuration initialization
2722 config
= config
|| {};
2725 this.$indicator
= null;
2726 this.indicator
= null;
2727 this.indicatorTitle
= null;
2730 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
2731 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
2732 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
2737 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
2739 /* Static Properties */
2742 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2743 * The static property will be overridden if the #indicator configuration is used.
2747 * @property {string|null}
2749 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
2752 * A text string used as the indicator title, a function that returns title text, or `null`
2753 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
2757 * @property {string|Function|null}
2759 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
2764 * Set the indicator element.
2766 * If an element is already set, it will be cleaned up before setting up the new element.
2768 * @param {jQuery} $indicator Element to use as indicator
2770 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
2771 if ( this.$indicator
) {
2773 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
2774 .removeAttr( 'title' );
2777 this.$indicator
= $indicator
2778 .addClass( 'oo-ui-indicatorElement-indicator' )
2779 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
2780 if ( this.indicatorTitle
!== null ) {
2781 this.$indicator
.attr( 'title', this.indicatorTitle
);
2784 this.updateThemeClasses();
2788 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
2790 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
2793 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
2794 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
2796 if ( this.indicator
!== indicator
) {
2797 if ( this.$indicator
) {
2798 if ( this.indicator
!== null ) {
2799 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
2801 if ( indicator
!== null ) {
2802 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
2805 this.indicator
= indicator
;
2808 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
2809 this.updateThemeClasses();
2815 * Set the indicator title.
2817 * The title is displayed when a user moves the mouse over the indicator.
2819 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
2820 * `null` for no indicator title
2823 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
2824 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
2825 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
2826 OO
.ui
.resolveMsg( indicatorTitle
) : null;
2828 if ( this.indicatorTitle
!== indicatorTitle
) {
2829 this.indicatorTitle
= indicatorTitle
;
2830 if ( this.$indicator
) {
2831 if ( this.indicatorTitle
!== null ) {
2832 this.$indicator
.attr( 'title', indicatorTitle
);
2834 this.$indicator
.removeAttr( 'title' );
2843 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2845 * @return {string} Symbolic name of indicator
2847 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
2848 return this.indicator
;
2852 * Get the indicator title.
2854 * The title is displayed when a user moves the mouse over the indicator.
2856 * @return {string} Indicator title text
2858 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
2859 return this.indicatorTitle
;
2863 * LabelElement is often mixed into other classes to generate a label, which
2864 * helps identify the function of an interface element.
2865 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
2867 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2873 * @param {Object} [config] Configuration options
2874 * @cfg {jQuery} [$label] The label element created by the class. If this
2875 * configuration is omitted, the label element will use a generated `<span>`.
2876 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2877 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2878 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
2879 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2881 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
2882 // Configuration initialization
2883 config
= config
|| {};
2890 this.setLabel( config
.label
|| this.constructor.static.label
);
2891 this.setLabelElement( config
.$label
|| $( '<span>' ) );
2896 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
2901 * @event labelChange
2902 * @param {string} value
2905 /* Static Properties */
2908 * The label text. The label can be specified as a plaintext string, a function that will
2909 * produce a string in the future, or `null` for no label. The static value will
2910 * be overridden if a label is specified with the #label config option.
2914 * @property {string|Function|null}
2916 OO
.ui
.mixin
.LabelElement
.static.label
= null;
2918 /* Static methods */
2921 * Highlight the first occurrence of the query in the given text
2923 * @param {string} text Text
2924 * @param {string} query Query to find
2925 * @return {jQuery} Text with the first match of the query
2926 * sub-string wrapped in highlighted span
2928 OO
.ui
.mixin
.LabelElement
.static.highlightQuery = function ( text
, query
) {
2929 var $result
= $( '<span>' ),
2930 offset
= text
.toLowerCase().indexOf( query
.toLowerCase() );
2932 if ( !query
.length
|| offset
=== -1 ) {
2933 return $result
.text( text
);
2936 document
.createTextNode( text
.slice( 0, offset
) ),
2938 .addClass( 'oo-ui-labelElement-label-highlight' )
2939 .text( text
.slice( offset
, offset
+ query
.length
) ),
2940 document
.createTextNode( text
.slice( offset
+ query
.length
) )
2942 return $result
.contents();
2948 * Set the label element.
2950 * If an element is already set, it will be cleaned up before setting up the new element.
2952 * @param {jQuery} $label Element to use as label
2954 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
2955 if ( this.$label
) {
2956 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
2959 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
2960 this.setLabelContent( this.label
);
2966 * An empty string will result in the label being hidden. A string containing only whitespace will
2967 * be converted to a single ` `.
2969 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2970 * text; or null for no label
2973 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
2974 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
2975 label
= ( ( typeof label
=== 'string' || label
instanceof jQuery
) && label
.length
) || ( label
instanceof OO
.ui
.HtmlSnippet
&& label
.toString().length
) ? label
: null;
2977 if ( this.label
!== label
) {
2978 if ( this.$label
) {
2979 this.setLabelContent( label
);
2982 this.emit( 'labelChange' );
2985 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
);
2991 * Set the label as plain text with a highlighted query
2993 * @param {string} text Text label to set
2994 * @param {string} query Substring of text to highlight
2997 OO
.ui
.mixin
.LabelElement
.prototype.setHighlightedQuery = function ( text
, query
) {
2998 return this.setLabel( this.constructor.static.highlightQuery( text
, query
) );
3004 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
3005 * text; or null for no label
3007 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
3012 * Set the content of the label.
3014 * Do not call this method until after the label element has been set by #setLabelElement.
3017 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
3018 * text; or null for no label
3020 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
3021 if ( typeof label
=== 'string' ) {
3022 if ( label
.match( /^\s*$/ ) ) {
3023 // Convert whitespace only string to a single non-breaking space
3024 this.$label
.html( ' ' );
3026 this.$label
.text( label
);
3028 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
3029 this.$label
.html( label
.toString() );
3030 } else if ( label
instanceof jQuery
) {
3031 this.$label
.empty().append( label
);
3033 this.$label
.empty();
3038 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
3039 * additional functionality to an element created by another class. The class provides
3040 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
3041 * which are used to customize the look and feel of a widget to better describe its
3042 * importance and functionality.
3044 * The library currently contains the following styling flags for general use:
3046 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
3047 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
3048 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
3050 * The flags affect the appearance of the buttons:
3053 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
3054 * var button1 = new OO.ui.ButtonWidget( {
3055 * label: 'Constructive',
3056 * flags: 'constructive'
3058 * var button2 = new OO.ui.ButtonWidget( {
3059 * label: 'Destructive',
3060 * flags: 'destructive'
3062 * var button3 = new OO.ui.ButtonWidget( {
3063 * label: 'Progressive',
3064 * flags: 'progressive'
3066 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
3068 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
3069 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
3071 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
3077 * @param {Object} [config] Configuration options
3078 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
3079 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
3080 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
3081 * @cfg {jQuery} [$flagged] The flagged element. By default,
3082 * the flagged functionality is applied to the element created by the class ($element).
3083 * If a different element is specified, the flagged functionality will be applied to it instead.
3085 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
3086 // Configuration initialization
3087 config
= config
|| {};
3091 this.$flagged
= null;
3094 this.setFlags( config
.flags
);
3095 this.setFlaggedElement( config
.$flagged
|| this.$element
);
3102 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3103 * parameter contains the name of each modified flag and indicates whether it was
3106 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3107 * that the flag was added, `false` that the flag was removed.
3113 * Set the flagged element.
3115 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
3116 * If an element is already set, the method will remove the mixin’s effect on that element.
3118 * @param {jQuery} $flagged Element that should be flagged
3120 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
3121 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
3122 return 'oo-ui-flaggedElement-' + flag
;
3125 if ( this.$flagged
) {
3126 this.$flagged
.removeClass( classNames
);
3129 this.$flagged
= $flagged
.addClass( classNames
);
3133 * Check if the specified flag is set.
3135 * @param {string} flag Name of flag
3136 * @return {boolean} The flag is set
3138 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
3139 // This may be called before the constructor, thus before this.flags is set
3140 return this.flags
&& ( flag
in this.flags
);
3144 * Get the names of all flags set.
3146 * @return {string[]} Flag names
3148 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
3149 // This may be called before the constructor, thus before this.flags is set
3150 return Object
.keys( this.flags
|| {} );
3159 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
3160 var flag
, className
,
3163 classPrefix
= 'oo-ui-flaggedElement-';
3165 for ( flag
in this.flags
) {
3166 className
= classPrefix
+ flag
;
3167 changes
[ flag
] = false;
3168 delete this.flags
[ flag
];
3169 remove
.push( className
);
3172 if ( this.$flagged
) {
3173 this.$flagged
.removeClass( remove
.join( ' ' ) );
3176 this.updateThemeClasses();
3177 this.emit( 'flag', changes
);
3183 * Add one or more flags.
3185 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3186 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3187 * be added (`true`) or removed (`false`).
3191 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
3192 var i
, len
, flag
, className
,
3196 classPrefix
= 'oo-ui-flaggedElement-';
3198 if ( typeof flags
=== 'string' ) {
3199 className
= classPrefix
+ flags
;
3201 if ( !this.flags
[ flags
] ) {
3202 this.flags
[ flags
] = true;
3203 add
.push( className
);
3205 } else if ( Array
.isArray( flags
) ) {
3206 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
3208 className
= classPrefix
+ flag
;
3210 if ( !this.flags
[ flag
] ) {
3211 changes
[ flag
] = true;
3212 this.flags
[ flag
] = true;
3213 add
.push( className
);
3216 } else if ( OO
.isPlainObject( flags
) ) {
3217 for ( flag
in flags
) {
3218 className
= classPrefix
+ flag
;
3219 if ( flags
[ flag
] ) {
3221 if ( !this.flags
[ flag
] ) {
3222 changes
[ flag
] = true;
3223 this.flags
[ flag
] = true;
3224 add
.push( className
);
3228 if ( this.flags
[ flag
] ) {
3229 changes
[ flag
] = false;
3230 delete this.flags
[ flag
];
3231 remove
.push( className
);
3237 if ( this.$flagged
) {
3239 .addClass( add
.join( ' ' ) )
3240 .removeClass( remove
.join( ' ' ) );
3243 this.updateThemeClasses();
3244 this.emit( 'flag', changes
);
3250 * TitledElement is mixed into other classes to provide a `title` attribute.
3251 * Titles are rendered by the browser and are made visible when the user moves
3252 * the mouse over the element. Titles are not visible on touch devices.
3255 * // TitledElement provides a 'title' attribute to the
3256 * // ButtonWidget class
3257 * var button = new OO.ui.ButtonWidget( {
3258 * label: 'Button with Title',
3259 * title: 'I am a button'
3261 * $( 'body' ).append( button.$element );
3267 * @param {Object} [config] Configuration options
3268 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3269 * If this config is omitted, the title functionality is applied to $element, the
3270 * element created by the class.
3271 * @cfg {string|Function} [title] The title text or a function that returns text. If
3272 * this config is omitted, the value of the {@link #static-title static title} property is used.
3274 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
3275 // Configuration initialization
3276 config
= config
|| {};
3279 this.$titled
= null;
3283 this.setTitle( config
.title
!== undefined ? config
.title
: this.constructor.static.title
);
3284 this.setTitledElement( config
.$titled
|| this.$element
);
3289 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
3291 /* Static Properties */
3294 * The title text, a function that returns text, or `null` for no title. The value of the static property
3295 * is overridden if the #title config option is used.
3299 * @property {string|Function|null}
3301 OO
.ui
.mixin
.TitledElement
.static.title
= null;
3306 * Set the titled element.
3308 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
3309 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3311 * @param {jQuery} $titled Element that should use the 'titled' functionality
3313 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
3314 if ( this.$titled
) {
3315 this.$titled
.removeAttr( 'title' );
3318 this.$titled
= $titled
;
3320 this.$titled
.attr( 'title', this.title
);
3327 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3330 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
3331 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
3332 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
3334 if ( this.title
!== title
) {
3335 if ( this.$titled
) {
3336 if ( title
!== null ) {
3337 this.$titled
.attr( 'title', title
);
3339 this.$titled
.removeAttr( 'title' );
3351 * @return {string} Title string
3353 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
3358 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3359 * Accesskeys allow an user to go to a specific element by using
3360 * a shortcut combination of a browser specific keys + the key
3364 * // AccessKeyedElement provides an 'accesskey' attribute to the
3365 * // ButtonWidget class
3366 * var button = new OO.ui.ButtonWidget( {
3367 * label: 'Button with Accesskey',
3370 * $( 'body' ).append( button.$element );
3376 * @param {Object} [config] Configuration options
3377 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3378 * If this config is omitted, the accesskey functionality is applied to $element, the
3379 * element created by the class.
3380 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3381 * this config is omitted, no accesskey will be added.
3383 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
3384 // Configuration initialization
3385 config
= config
|| {};
3388 this.$accessKeyed
= null;
3389 this.accessKey
= null;
3392 this.setAccessKey( config
.accessKey
|| null );
3393 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
3398 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
3400 /* Static Properties */
3403 * The access key, a function that returns a key, or `null` for no accesskey.
3407 * @property {string|Function|null}
3409 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
3414 * Set the accesskeyed element.
3416 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3417 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3419 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
3421 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
3422 if ( this.$accessKeyed
) {
3423 this.$accessKeyed
.removeAttr( 'accesskey' );
3426 this.$accessKeyed
= $accessKeyed
;
3427 if ( this.accessKey
) {
3428 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
3435 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3438 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
3439 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
3441 if ( this.accessKey
!== accessKey
) {
3442 if ( this.$accessKeyed
) {
3443 if ( accessKey
!== null ) {
3444 this.$accessKeyed
.attr( 'accesskey', accessKey
);
3446 this.$accessKeyed
.removeAttr( 'accesskey' );
3449 this.accessKey
= accessKey
;
3458 * @return {string} accessKey string
3460 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
3461 return this.accessKey
;
3465 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3466 * feels, and functionality can be customized via the class’s configuration options
3467 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
3470 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
3473 * // A button widget
3474 * var button = new OO.ui.ButtonWidget( {
3475 * label: 'Button with Icon',
3477 * iconTitle: 'Remove'
3479 * $( 'body' ).append( button.$element );
3481 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3484 * @extends OO.ui.Widget
3485 * @mixins OO.ui.mixin.ButtonElement
3486 * @mixins OO.ui.mixin.IconElement
3487 * @mixins OO.ui.mixin.IndicatorElement
3488 * @mixins OO.ui.mixin.LabelElement
3489 * @mixins OO.ui.mixin.TitledElement
3490 * @mixins OO.ui.mixin.FlaggedElement
3491 * @mixins OO.ui.mixin.TabIndexedElement
3492 * @mixins OO.ui.mixin.AccessKeyedElement
3495 * @param {Object} [config] Configuration options
3496 * @cfg {boolean} [active=false] Whether button should be shown as active
3497 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3498 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3499 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3501 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
3502 // Configuration initialization
3503 config
= config
|| {};
3505 // Parent constructor
3506 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
3508 // Mixin constructors
3509 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3510 OO
.ui
.mixin
.IconElement
.call( this, config
);
3511 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3512 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3513 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
3514 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3515 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
3516 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
3521 this.noFollow
= false;
3524 this.connect( this, { disable
: 'onDisable' } );
3527 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3529 .addClass( 'oo-ui-buttonWidget' )
3530 .append( this.$button
);
3531 this.setActive( config
.active
);
3532 this.setHref( config
.href
);
3533 this.setTarget( config
.target
);
3534 this.setNoFollow( config
.noFollow
);
3539 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
3540 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
3541 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
3542 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
3543 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
3544 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
3545 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
3546 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3547 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
3549 /* Static Properties */
3555 OO
.ui
.ButtonWidget
.static.cancelButtonMouseDownEvents
= false;
3561 OO
.ui
.ButtonWidget
.static.tagName
= 'span';
3566 * Get hyperlink location.
3568 * @return {string} Hyperlink location
3570 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
3575 * Get hyperlink target.
3577 * @return {string} Hyperlink target
3579 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
3584 * Get search engine traversal hint.
3586 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3588 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
3589 return this.noFollow
;
3593 * Set hyperlink location.
3595 * @param {string|null} href Hyperlink location, null to remove
3597 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
3598 href
= typeof href
=== 'string' ? href
: null;
3599 if ( href
!== null && !OO
.ui
.isSafeUrl( href
) ) {
3603 if ( href
!== this.href
) {
3612 * Update the `href` attribute, in case of changes to href or
3618 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
3619 if ( this.href
!== null && !this.isDisabled() ) {
3620 this.$button
.attr( 'href', this.href
);
3622 this.$button
.removeAttr( 'href' );
3629 * Handle disable events.
3632 * @param {boolean} disabled Element is disabled
3634 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
3639 * Set hyperlink target.
3641 * @param {string|null} target Hyperlink target, null to remove
3643 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
3644 target
= typeof target
=== 'string' ? target
: null;
3646 if ( target
!== this.target
) {
3647 this.target
= target
;
3648 if ( target
!== null ) {
3649 this.$button
.attr( 'target', target
);
3651 this.$button
.removeAttr( 'target' );
3659 * Set search engine traversal hint.
3661 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3663 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
3664 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
3666 if ( noFollow
!== this.noFollow
) {
3667 this.noFollow
= noFollow
;
3669 this.$button
.attr( 'rel', 'nofollow' );
3671 this.$button
.removeAttr( 'rel' );
3678 // Override method visibility hints from ButtonElement
3689 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3690 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3691 * removed, and cleared from the group.
3694 * // Example: A ButtonGroupWidget with two buttons
3695 * var button1 = new OO.ui.PopupButtonWidget( {
3696 * label: 'Select a category',
3699 * $content: $( '<p>List of categories...</p>' ),
3704 * var button2 = new OO.ui.ButtonWidget( {
3707 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3708 * items: [button1, button2]
3710 * $( 'body' ).append( buttonGroup.$element );
3713 * @extends OO.ui.Widget
3714 * @mixins OO.ui.mixin.GroupElement
3717 * @param {Object} [config] Configuration options
3718 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3720 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
3721 // Configuration initialization
3722 config
= config
|| {};
3724 // Parent constructor
3725 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
3727 // Mixin constructors
3728 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
3731 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
3732 if ( Array
.isArray( config
.items
) ) {
3733 this.addItems( config
.items
);
3739 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
3740 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
3742 /* Static Properties */
3748 OO
.ui
.ButtonGroupWidget
.static.tagName
= 'span';
3751 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3752 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
3753 * for a list of icons included in the library.
3756 * // An icon widget with a label
3757 * var myIcon = new OO.ui.IconWidget( {
3761 * // Create a label.
3762 * var iconLabel = new OO.ui.LabelWidget( {
3765 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3767 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
3770 * @extends OO.ui.Widget
3771 * @mixins OO.ui.mixin.IconElement
3772 * @mixins OO.ui.mixin.TitledElement
3773 * @mixins OO.ui.mixin.FlaggedElement
3776 * @param {Object} [config] Configuration options
3778 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
3779 // Configuration initialization
3780 config
= config
|| {};
3782 // Parent constructor
3783 OO
.ui
.IconWidget
.parent
.call( this, config
);
3785 // Mixin constructors
3786 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
3787 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3788 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
3791 this.$element
.addClass( 'oo-ui-iconWidget' );
3796 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
3797 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
3798 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
3799 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
3801 /* Static Properties */
3807 OO
.ui
.IconWidget
.static.tagName
= 'span';
3810 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
3811 * attention to the status of an item or to clarify the function of a control. For a list of
3812 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
3815 * // Example of an indicator widget
3816 * var indicator1 = new OO.ui.IndicatorWidget( {
3817 * indicator: 'alert'
3820 * // Create a fieldset layout to add a label
3821 * var fieldset = new OO.ui.FieldsetLayout();
3822 * fieldset.addItems( [
3823 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
3825 * $( 'body' ).append( fieldset.$element );
3827 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3830 * @extends OO.ui.Widget
3831 * @mixins OO.ui.mixin.IndicatorElement
3832 * @mixins OO.ui.mixin.TitledElement
3835 * @param {Object} [config] Configuration options
3837 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
3838 // Configuration initialization
3839 config
= config
|| {};
3841 // Parent constructor
3842 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
3844 // Mixin constructors
3845 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
3846 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3849 this.$element
.addClass( 'oo-ui-indicatorWidget' );
3854 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
3855 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
3856 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
3858 /* Static Properties */
3864 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
3867 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
3868 * be configured with a `label` option that is set to a string, a label node, or a function:
3870 * - String: a plaintext string
3871 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
3872 * label that includes a link or special styling, such as a gray color or additional graphical elements.
3873 * - Function: a function that will produce a string in the future. Functions are used
3874 * in cases where the value of the label is not currently defined.
3876 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
3877 * will come into focus when the label is clicked.
3880 * // Examples of LabelWidgets
3881 * var label1 = new OO.ui.LabelWidget( {
3882 * label: 'plaintext label'
3884 * var label2 = new OO.ui.LabelWidget( {
3885 * label: $( '<a href="default.html">jQuery label</a>' )
3887 * // Create a fieldset layout with fields for each example
3888 * var fieldset = new OO.ui.FieldsetLayout();
3889 * fieldset.addItems( [
3890 * new OO.ui.FieldLayout( label1 ),
3891 * new OO.ui.FieldLayout( label2 )
3893 * $( 'body' ).append( fieldset.$element );
3896 * @extends OO.ui.Widget
3897 * @mixins OO.ui.mixin.LabelElement
3898 * @mixins OO.ui.mixin.TitledElement
3901 * @param {Object} [config] Configuration options
3902 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
3903 * Clicking the label will focus the specified input field.
3905 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
3906 // Configuration initialization
3907 config
= config
|| {};
3909 // Parent constructor
3910 OO
.ui
.LabelWidget
.parent
.call( this, config
);
3912 // Mixin constructors
3913 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
3914 OO
.ui
.mixin
.TitledElement
.call( this, config
);
3917 this.input
= config
.input
;
3921 if ( this.input
.getInputId() ) {
3922 this.$element
.attr( 'for', this.input
.getInputId() );
3924 this.$label
.on( 'click', function () {
3930 this.$element
.addClass( 'oo-ui-labelWidget' );
3935 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
3936 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
3937 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
3939 /* Static Properties */
3945 OO
.ui
.LabelWidget
.static.tagName
= 'label';
3948 * PendingElement is a mixin that is used to create elements that notify users that something is happening
3949 * and that they should wait before proceeding. The pending state is visually represented with a pending
3950 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
3951 * field of a {@link OO.ui.TextInputWidget text input widget}.
3953 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
3954 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
3955 * in process dialogs.
3958 * function MessageDialog( config ) {
3959 * MessageDialog.parent.call( this, config );
3961 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
3963 * MessageDialog.static.name = 'myMessageDialog';
3964 * MessageDialog.static.actions = [
3965 * { action: 'save', label: 'Done', flags: 'primary' },
3966 * { label: 'Cancel', flags: 'safe' }
3969 * MessageDialog.prototype.initialize = function () {
3970 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
3971 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
3972 * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending state. Note that action widgets can be marked pending in message dialogs but not process dialogs.</p>' );
3973 * this.$body.append( this.content.$element );
3975 * MessageDialog.prototype.getBodyHeight = function () {
3978 * MessageDialog.prototype.getActionProcess = function ( action ) {
3979 * var dialog = this;
3980 * if ( action === 'save' ) {
3981 * dialog.getActions().get({actions: 'save'})[0].pushPending();
3982 * return new OO.ui.Process()
3984 * .next( function () {
3985 * dialog.getActions().get({actions: 'save'})[0].popPending();
3988 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
3991 * var windowManager = new OO.ui.WindowManager();
3992 * $( 'body' ).append( windowManager.$element );
3994 * var dialog = new MessageDialog();
3995 * windowManager.addWindows( [ dialog ] );
3996 * windowManager.openWindow( dialog );
4002 * @param {Object} [config] Configuration options
4003 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
4005 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
4006 // Configuration initialization
4007 config
= config
|| {};
4011 this.$pending
= null;
4014 this.setPendingElement( config
.$pending
|| this.$element
);
4019 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
4024 * Set the pending element (and clean up any existing one).
4026 * @param {jQuery} $pending The element to set to pending.
4028 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
4029 if ( this.$pending
) {
4030 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4033 this.$pending
= $pending
;
4034 if ( this.pending
> 0 ) {
4035 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4040 * Check if an element is pending.
4042 * @return {boolean} Element is pending
4044 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
4045 return !!this.pending
;
4049 * Increase the pending counter. The pending state will remain active until the counter is zero
4050 * (i.e., the number of calls to #pushPending and #popPending is the same).
4054 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
4055 if ( this.pending
=== 0 ) {
4056 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4057 this.updateThemeClasses();
4065 * Decrease the pending counter. The pending state will remain active until the counter is zero
4066 * (i.e., the number of calls to #pushPending and #popPending is the same).
4070 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
4071 if ( this.pending
=== 1 ) {
4072 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4073 this.updateThemeClasses();
4075 this.pending
= Math
.max( 0, this.pending
- 1 );
4081 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4082 * in the document (for example, in an OO.ui.Window's $overlay).
4084 * The elements's position is automatically calculated and maintained when window is resized or the
4085 * page is scrolled. If you reposition the container manually, you have to call #position to make
4086 * sure the element is still placed correctly.
4088 * As positioning is only possible when both the element and the container are attached to the DOM
4089 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4090 * the #toggle method to display a floating popup, for example.
4096 * @param {Object} [config] Configuration options
4097 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4098 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4099 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4100 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4101 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4102 * 'top': Align the top edge with $floatableContainer's top edge
4103 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4104 * 'center': Vertically align the center with $floatableContainer's center
4105 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4106 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4107 * 'after': Directly after $floatableContainer, algining f's start edge with fC's end edge
4108 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4109 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4110 * 'center': Horizontally align the center with $floatableContainer's center
4111 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4114 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
4115 // Configuration initialization
4116 config
= config
|| {};
4119 this.$floatable
= null;
4120 this.$floatableContainer
= null;
4121 this.$floatableWindow
= null;
4122 this.$floatableClosestScrollable
= null;
4123 this.onFloatableScrollHandler
= this.position
.bind( this );
4124 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
4127 this.setFloatableContainer( config
.$floatableContainer
);
4128 this.setFloatableElement( config
.$floatable
|| this.$element
);
4129 this.setVerticalPosition( config
.verticalPosition
|| 'below' );
4130 this.setHorizontalPosition( config
.horizontalPosition
|| 'start' );
4131 this.hideWhenOutOfView
= config
.hideWhenOutOfView
=== undefined ? true : !!config
.hideWhenOutOfView
;
4137 * Set floatable element.
4139 * If an element is already set, it will be cleaned up before setting up the new element.
4141 * @param {jQuery} $floatable Element to make floatable
4143 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
4144 if ( this.$floatable
) {
4145 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
4146 this.$floatable
.css( { left
: '', top
: '' } );
4149 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
4154 * Set floatable container.
4156 * The element will be positioned relative to the specified container.
4158 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4160 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
4161 this.$floatableContainer
= $floatableContainer
;
4162 if ( this.$floatable
) {
4168 * Change how the element is positioned vertically.
4170 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4172 OO
.ui
.mixin
.FloatableElement
.prototype.setVerticalPosition = function ( position
) {
4173 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position
) === -1 ) {
4174 throw new Error( 'Invalid value for vertical position: ' + position
);
4176 if ( this.verticalPosition
!== position
) {
4177 this.verticalPosition
= position
;
4178 if ( this.$floatable
) {
4185 * Change how the element is positioned horizontally.
4187 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4189 OO
.ui
.mixin
.FloatableElement
.prototype.setHorizontalPosition = function ( position
) {
4190 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position
) === -1 ) {
4191 throw new Error( 'Invalid value for horizontal position: ' + position
);
4193 if ( this.horizontalPosition
!== position
) {
4194 this.horizontalPosition
= position
;
4195 if ( this.$floatable
) {
4202 * Toggle positioning.
4204 * Do not turn positioning on until after the element is attached to the DOM and visible.
4206 * @param {boolean} [positioning] Enable positioning, omit to toggle
4209 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
4210 var closestScrollableOfContainer
;
4212 if ( !this.$floatable
|| !this.$floatableContainer
) {
4216 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
4218 if ( positioning
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4219 OO
.ui
.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4220 this.warnedUnattached
= true;
4223 if ( this.positioning
!== positioning
) {
4224 this.positioning
= positioning
;
4226 this.needsCustomPosition
=
4227 this.verticalPostion
!== 'below' ||
4228 this.horizontalPosition
!== 'start' ||
4229 !OO
.ui
.contains( this.$floatableContainer
[ 0 ], this.$floatable
[ 0 ] );
4231 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
4232 // If the scrollable is the root, we have to listen to scroll events
4233 // on the window because of browser inconsistencies.
4234 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
4235 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
4238 if ( positioning
) {
4239 this.$floatableWindow
= $( this.getElementWindow() );
4240 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
4242 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
4243 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
4245 // Initial position after visible
4248 if ( this.$floatableWindow
) {
4249 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
4250 this.$floatableWindow
= null;
4253 if ( this.$floatableClosestScrollable
) {
4254 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
4255 this.$floatableClosestScrollable
= null;
4258 this.$floatable
.css( { left
: '', right
: '', top
: '' } );
4266 * Check whether the bottom edge of the given element is within the viewport of the given container.
4269 * @param {jQuery} $element
4270 * @param {jQuery} $container
4273 OO
.ui
.mixin
.FloatableElement
.prototype.isElementInViewport = function ( $element
, $container
) {
4274 var elemRect
, contRect
, topEdgeInBounds
, bottomEdgeInBounds
, leftEdgeInBounds
, rightEdgeInBounds
,
4275 startEdgeInBounds
, endEdgeInBounds
,
4276 direction
= $element
.css( 'direction' );
4278 elemRect
= $element
[ 0 ].getBoundingClientRect();
4279 if ( $container
[ 0 ] === window
) {
4283 right
: document
.documentElement
.clientWidth
,
4284 bottom
: document
.documentElement
.clientHeight
4287 contRect
= $container
[ 0 ].getBoundingClientRect();
4290 topEdgeInBounds
= elemRect
.top
>= contRect
.top
&& elemRect
.top
<= contRect
.bottom
;
4291 bottomEdgeInBounds
= elemRect
.bottom
>= contRect
.top
&& elemRect
.bottom
<= contRect
.bottom
;
4292 leftEdgeInBounds
= elemRect
.left
>= contRect
.left
&& elemRect
.left
<= contRect
.right
;
4293 rightEdgeInBounds
= elemRect
.right
>= contRect
.left
&& elemRect
.right
<= contRect
.right
;
4294 if ( direction
=== 'rtl' ) {
4295 startEdgeInBounds
= rightEdgeInBounds
;
4296 endEdgeInBounds
= leftEdgeInBounds
;
4298 startEdgeInBounds
= leftEdgeInBounds
;
4299 endEdgeInBounds
= rightEdgeInBounds
;
4302 if ( this.verticalPosition
=== 'below' && !bottomEdgeInBounds
) {
4305 if ( this.verticalPosition
=== 'above' && !topEdgeInBounds
) {
4308 if ( this.horizontalPosition
=== 'before' && !startEdgeInBounds
) {
4311 if ( this.horizontalPosition
=== 'after' && !endEdgeInBounds
) {
4315 // The other positioning values are all about being inside the container,
4316 // so in those cases all we care about is that any part of the container is visible.
4317 return elemRect
.top
<= contRect
.bottom
&& elemRect
.bottom
>= contRect
.top
&&
4318 elemRect
.left
<= contRect
.right
&& elemRect
.right
>= contRect
.left
;
4322 * Position the floatable below its container.
4324 * This should only be done when both of them are attached to the DOM and visible.
4328 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
4329 if ( !this.positioning
) {
4334 // To continue, some things need to be true:
4335 // The element must actually be in the DOM
4336 this.isElementAttached() && (
4337 // The closest scrollable is the current window
4338 this.$floatableClosestScrollable
[ 0 ] === this.getElementWindow() ||
4339 // OR is an element in the element's DOM
4340 $.contains( this.getElementDocument(), this.$floatableClosestScrollable
[ 0 ] )
4343 // Abort early if important parts of the widget are no longer attached to the DOM
4347 if ( this.hideWhenOutOfView
&& !this.isElementInViewport( this.$floatableContainer
, this.$floatableClosestScrollable
) ) {
4348 this.$floatable
.addClass( 'oo-ui-element-hidden' );
4351 this.$floatable
.removeClass( 'oo-ui-element-hidden' );
4354 if ( !this.needsCustomPosition
) {
4358 this.$floatable
.css( this.computePosition() );
4360 // We updated the position, so re-evaluate the clipping state.
4361 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4362 // will not notice the need to update itself.)
4363 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
4364 // it not listen to the right events in the right places?
4373 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4374 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4375 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4377 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4379 OO
.ui
.mixin
.FloatableElement
.prototype.computePosition = function () {
4380 var isBody
, scrollableX
, scrollableY
, containerPos
,
4381 horizScrollbarHeight
, vertScrollbarWidth
, scrollTop
, scrollLeft
,
4382 newPos
= { top
: '', left
: '', bottom
: '', right
: '' },
4383 direction
= this.$floatableContainer
.css( 'direction' ),
4384 $offsetParent
= this.$floatable
.offsetParent();
4386 if ( $offsetParent
.is( 'html' ) ) {
4387 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4388 // <html> element, but they do work on the <body>
4389 $offsetParent
= $( $offsetParent
[ 0 ].ownerDocument
.body
);
4391 isBody
= $offsetParent
.is( 'body' );
4392 scrollableX
= $offsetParent
.css( 'overflow-x' ) === 'scroll' || $offsetParent
.css( 'overflow-x' ) === 'auto';
4393 scrollableY
= $offsetParent
.css( 'overflow-y' ) === 'scroll' || $offsetParent
.css( 'overflow-y' ) === 'auto';
4395 vertScrollbarWidth
= $offsetParent
.innerWidth() - $offsetParent
.prop( 'clientWidth' );
4396 horizScrollbarHeight
= $offsetParent
.innerHeight() - $offsetParent
.prop( 'clientHeight' );
4397 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container is the body,
4398 // or if it isn't scrollable
4399 scrollTop
= scrollableY
&& !isBody
? $offsetParent
.scrollTop() : 0;
4400 scrollLeft
= scrollableX
&& !isBody
? OO
.ui
.Element
.static.getScrollLeft( $offsetParent
[ 0 ] ) : 0;
4402 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4403 // if the <body> has a margin
4404 containerPos
= isBody
?
4405 this.$floatableContainer
.offset() :
4406 OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, $offsetParent
);
4407 containerPos
.bottom
= containerPos
.top
+ this.$floatableContainer
.outerHeight();
4408 containerPos
.right
= containerPos
.left
+ this.$floatableContainer
.outerWidth();
4409 containerPos
.start
= direction
=== 'rtl' ? containerPos
.right
: containerPos
.left
;
4410 containerPos
.end
= direction
=== 'rtl' ? containerPos
.left
: containerPos
.right
;
4412 if ( this.verticalPosition
=== 'below' ) {
4413 newPos
.top
= containerPos
.bottom
;
4414 } else if ( this.verticalPosition
=== 'above' ) {
4415 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.top
;
4416 } else if ( this.verticalPosition
=== 'top' ) {
4417 newPos
.top
= containerPos
.top
;
4418 } else if ( this.verticalPosition
=== 'bottom' ) {
4419 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.bottom
;
4420 } else if ( this.verticalPosition
=== 'center' ) {
4421 newPos
.top
= containerPos
.top
+
4422 ( this.$floatableContainer
.height() - this.$floatable
.height() ) / 2;
4425 if ( this.horizontalPosition
=== 'before' ) {
4426 newPos
.end
= containerPos
.start
;
4427 } else if ( this.horizontalPosition
=== 'after' ) {
4428 newPos
.start
= containerPos
.end
;
4429 } else if ( this.horizontalPosition
=== 'start' ) {
4430 newPos
.start
= containerPos
.start
;
4431 } else if ( this.horizontalPosition
=== 'end' ) {
4432 newPos
.end
= containerPos
.end
;
4433 } else if ( this.horizontalPosition
=== 'center' ) {
4434 newPos
.left
= containerPos
.left
+
4435 ( this.$floatableContainer
.width() - this.$floatable
.width() ) / 2;
4438 if ( newPos
.start
!== undefined ) {
4439 if ( direction
=== 'rtl' ) {
4440 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.start
;
4442 newPos
.left
= newPos
.start
;
4444 delete newPos
.start
;
4446 if ( newPos
.end
!== undefined ) {
4447 if ( direction
=== 'rtl' ) {
4448 newPos
.left
= newPos
.end
;
4450 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.end
;
4455 // Account for scroll position
4456 if ( newPos
.top
!== '' ) {
4457 newPos
.top
+= scrollTop
;
4459 if ( newPos
.bottom
!== '' ) {
4460 newPos
.bottom
-= scrollTop
;
4462 if ( newPos
.left
!== '' ) {
4463 newPos
.left
+= scrollLeft
;
4465 if ( newPos
.right
!== '' ) {
4466 newPos
.right
-= scrollLeft
;
4469 // Account for scrollbar gutter
4470 if ( newPos
.bottom
!== '' ) {
4471 newPos
.bottom
-= horizScrollbarHeight
;
4473 if ( direction
=== 'rtl' ) {
4474 if ( newPos
.left
!== '' ) {
4475 newPos
.left
-= vertScrollbarWidth
;
4478 if ( newPos
.right
!== '' ) {
4479 newPos
.right
-= vertScrollbarWidth
;
4487 * Element that can be automatically clipped to visible boundaries.
4489 * Whenever the element's natural height changes, you have to call
4490 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4491 * clipping correctly.
4493 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4494 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4495 * then #$clippable will be given a fixed reduced height and/or width and will be made
4496 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4497 * but you can build a static footer by setting #$clippableContainer to an element that contains
4498 * #$clippable and the footer.
4504 * @param {Object} [config] Configuration options
4505 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4506 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4507 * omit to use #$clippable
4509 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
4510 // Configuration initialization
4511 config
= config
|| {};
4514 this.$clippable
= null;
4515 this.$clippableContainer
= null;
4516 this.clipping
= false;
4517 this.clippedHorizontally
= false;
4518 this.clippedVertically
= false;
4519 this.$clippableScrollableContainer
= null;
4520 this.$clippableScroller
= null;
4521 this.$clippableWindow
= null;
4522 this.idealWidth
= null;
4523 this.idealHeight
= null;
4524 this.onClippableScrollHandler
= this.clip
.bind( this );
4525 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
4528 if ( config
.$clippableContainer
) {
4529 this.setClippableContainer( config
.$clippableContainer
);
4531 this.setClippableElement( config
.$clippable
|| this.$element
);
4537 * Set clippable element.
4539 * If an element is already set, it will be cleaned up before setting up the new element.
4541 * @param {jQuery} $clippable Element to make clippable
4543 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
4544 if ( this.$clippable
) {
4545 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
4546 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
4547 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4550 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
4555 * Set clippable container.
4557 * This is the container that will be measured when deciding whether to clip. When clipping,
4558 * #$clippable will be resized in order to keep the clippable container fully visible.
4560 * If the clippable container is unset, #$clippable will be used.
4562 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4564 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
4565 this.$clippableContainer
= $clippableContainer
;
4566 if ( this.$clippable
) {
4574 * Do not turn clipping on until after the element is attached to the DOM and visible.
4576 * @param {boolean} [clipping] Enable clipping, omit to toggle
4579 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
4580 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
4582 if ( clipping
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4583 OO
.ui
.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4584 this.warnedUnattached
= true;
4587 if ( this.clipping
!== clipping
) {
4588 this.clipping
= clipping
;
4590 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
4591 // If the clippable container is the root, we have to listen to scroll events and check
4592 // jQuery.scrollTop on the window because of browser inconsistencies
4593 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4594 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
4595 this.$clippableScrollableContainer
;
4596 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
4597 this.$clippableWindow
= $( this.getElementWindow() )
4598 .on( 'resize', this.onClippableWindowResizeHandler
);
4599 // Initial clip after visible
4602 this.$clippable
.css( {
4610 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4612 this.$clippableScrollableContainer
= null;
4613 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
4614 this.$clippableScroller
= null;
4615 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
4616 this.$clippableWindow
= null;
4624 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4626 * @return {boolean} Element will be clipped to the visible area
4628 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
4629 return this.clipping
;
4633 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4635 * @return {boolean} Part of the element is being clipped
4637 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
4638 return this.clippedHorizontally
|| this.clippedVertically
;
4642 * Check if the right of the element is being clipped by the nearest scrollable container.
4644 * @return {boolean} Part of the element is being clipped
4646 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
4647 return this.clippedHorizontally
;
4651 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4653 * @return {boolean} Part of the element is being clipped
4655 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
4656 return this.clippedVertically
;
4660 * Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
4662 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4663 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4665 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
4666 this.idealWidth
= width
;
4667 this.idealHeight
= height
;
4669 if ( !this.clipping
) {
4670 // Update dimensions
4671 this.$clippable
.css( { width
: width
, height
: height
} );
4673 // While clipping, idealWidth and idealHeight are not considered
4677 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4678 * when the element's natural height changes.
4680 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4681 * overlapped by, the visible area of the nearest scrollable container.
4683 * Because calling clip() when the natural height changes isn't always possible, we also set
4684 * max-height when the element isn't being clipped. This means that if the element tries to grow
4685 * beyond the edge, something reasonable will happen before clip() is called.
4689 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
4690 var $container
, extraHeight
, extraWidth
, ccOffset
,
4691 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
4692 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
4693 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
4694 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
4695 buffer
= 7; // Chosen by fair dice roll
4697 if ( !this.clipping
) {
4698 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4702 $container
= this.$clippableContainer
|| this.$clippable
;
4703 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
4704 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
4705 ccOffset
= $container
.offset();
4706 if ( this.$clippableScrollableContainer
.is( 'html, body' ) ) {
4707 $scrollableContainer
= this.$clippableWindow
;
4708 scOffset
= { top
: 0, left
: 0 };
4710 $scrollableContainer
= this.$clippableScrollableContainer
;
4711 scOffset
= $scrollableContainer
.offset();
4713 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
4714 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
4715 ccWidth
= $container
.outerWidth() + buffer
;
4716 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
4717 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
4718 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
4719 desiredWidth
= ccOffset
.left
< 0 ?
4720 ccWidth
+ ccOffset
.left
:
4721 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
4722 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
4723 // It should never be desirable to exceed the dimensions of the browser viewport... right?
4724 desiredWidth
= Math
.min( desiredWidth
, document
.documentElement
.clientWidth
);
4725 desiredHeight
= Math
.min( desiredHeight
, document
.documentElement
.clientHeight
);
4726 allotedWidth
= Math
.ceil( desiredWidth
- extraWidth
);
4727 allotedHeight
= Math
.ceil( desiredHeight
- extraHeight
);
4728 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
4729 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
4730 clipWidth
= allotedWidth
< naturalWidth
;
4731 clipHeight
= allotedHeight
< naturalHeight
;
4734 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. (T157672)
4735 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
4736 this.$clippable
.css( 'overflowX', 'scroll' );
4737 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
4738 this.$clippable
.css( {
4739 width
: Math
.max( 0, allotedWidth
),
4743 this.$clippable
.css( {
4745 width
: this.idealWidth
|| '',
4746 maxWidth
: Math
.max( 0, allotedWidth
)
4750 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. (T157672)
4751 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
4752 this.$clippable
.css( 'overflowY', 'scroll' );
4753 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
4754 this.$clippable
.css( {
4755 height
: Math
.max( 0, allotedHeight
),
4759 this.$clippable
.css( {
4761 height
: this.idealHeight
|| '',
4762 maxHeight
: Math
.max( 0, allotedHeight
)
4766 // If we stopped clipping in at least one of the dimensions
4767 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
4768 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4771 this.clippedHorizontally
= clipWidth
;
4772 this.clippedVertically
= clipHeight
;
4778 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
4779 * By default, each popup has an anchor that points toward its origin.
4780 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
4782 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
4785 * // A popup widget.
4786 * var popup = new OO.ui.PopupWidget( {
4787 * $content: $( '<p>Hi there!</p>' ),
4792 * $( 'body' ).append( popup.$element );
4793 * // To display the popup, toggle the visibility to 'true'.
4794 * popup.toggle( true );
4796 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
4799 * @extends OO.ui.Widget
4800 * @mixins OO.ui.mixin.LabelElement
4801 * @mixins OO.ui.mixin.ClippableElement
4802 * @mixins OO.ui.mixin.FloatableElement
4805 * @param {Object} [config] Configuration options
4806 * @cfg {number} [width=320] Width of popup in pixels
4807 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
4808 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
4809 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
4810 * 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
4811 * of $floatableContainer
4812 * 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
4813 * of $floatableContainer
4814 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
4815 * endwards (right/left) to the vertical center of $floatableContainer
4816 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
4817 * startwards (left/right) to the vertical center of $floatableContainer
4818 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
4819 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in RTL)
4820 * as possible while still keeping the anchor within the popup;
4821 * if position is before/after, move the popup as far downwards as possible.
4822 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in RTL)
4823 * as possible while still keeping the anchor within the popup;
4824 * if position in before/after, move the popup as far upwards as possible.
4825 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the center
4826 * of the popup with the center of $floatableContainer.
4827 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
4828 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
4829 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
4830 * See the [OOjs UI docs on MediaWiki][3] for an example.
4831 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
4832 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
4833 * @cfg {jQuery} [$content] Content to append to the popup's body
4834 * @cfg {jQuery} [$footer] Content to append to the popup's footer
4835 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
4836 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
4837 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
4839 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
4840 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
4842 * @cfg {boolean} [padded=false] Add padding to the popup's body
4844 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
4845 // Configuration initialization
4846 config
= config
|| {};
4848 // Parent constructor
4849 OO
.ui
.PopupWidget
.parent
.call( this, config
);
4851 // Properties (must be set before ClippableElement constructor call)
4852 this.$body
= $( '<div>' );
4853 this.$popup
= $( '<div>' );
4855 // Mixin constructors
4856 OO
.ui
.mixin
.LabelElement
.call( this, config
);
4857 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
4858 $clippable
: this.$body
,
4859 $clippableContainer
: this.$popup
4861 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
4864 this.$anchor
= $( '<div>' );
4865 // If undefined, will be computed lazily in updateDimensions()
4866 this.$container
= config
.$container
;
4867 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
4868 this.autoClose
= !!config
.autoClose
;
4869 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
4870 this.transitionTimeout
= null;
4871 this.anchored
= false;
4872 this.width
= config
.width
!== undefined ? config
.width
: 320;
4873 this.height
= config
.height
!== undefined ? config
.height
: null;
4874 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4875 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
4878 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
4879 this.setAlignment( config
.align
|| 'center' );
4880 this.setPosition( config
.position
|| 'below' );
4881 this.$body
.addClass( 'oo-ui-popupWidget-body' );
4882 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
4884 .addClass( 'oo-ui-popupWidget-popup' )
4885 .append( this.$body
);
4887 .addClass( 'oo-ui-popupWidget' )
4888 .append( this.$popup
, this.$anchor
);
4889 // Move content, which was added to #$element by OO.ui.Widget, to the body
4890 // FIXME This is gross, we should use '$body' or something for the config
4891 if ( config
.$content
instanceof jQuery
) {
4892 this.$body
.append( config
.$content
);
4895 if ( config
.padded
) {
4896 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
4899 if ( config
.head
) {
4900 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
4901 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
4902 this.$head
= $( '<div>' )
4903 .addClass( 'oo-ui-popupWidget-head' )
4904 .append( this.$label
, this.closeButton
.$element
);
4905 this.$popup
.prepend( this.$head
);
4908 if ( config
.$footer
) {
4909 this.$footer
= $( '<div>' )
4910 .addClass( 'oo-ui-popupWidget-footer' )
4911 .append( config
.$footer
);
4912 this.$popup
.append( this.$footer
);
4915 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
4916 // that reference properties not initialized at that time of parent class construction
4917 // TODO: Find a better way to handle post-constructor setup
4918 this.visible
= false;
4919 this.$element
.addClass( 'oo-ui-element-hidden' );
4924 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
4925 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
4926 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
4927 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.FloatableElement
);
4934 * The popup is ready: it is visible and has been positioned and clipped.
4940 * Handles mouse down events.
4943 * @param {MouseEvent} e Mouse down event
4945 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
4948 !OO
.ui
.contains( this.$element
.add( this.$autoCloseIgnore
).get(), e
.target
, true )
4950 this.toggle( false );
4955 * Bind mouse down listener.
4959 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
4960 // Capture clicks outside popup
4961 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
4965 * Handles close button click events.
4969 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
4970 if ( this.isVisible() ) {
4971 this.toggle( false );
4976 * Unbind mouse down listener.
4980 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
4981 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
4985 * Handles key down events.
4988 * @param {KeyboardEvent} e Key down event
4990 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
4992 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
4995 this.toggle( false );
4997 e
.stopPropagation();
5002 * Bind key down listener.
5006 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
5007 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5011 * Unbind key down listener.
5015 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
5016 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5020 * Show, hide, or toggle the visibility of the anchor.
5022 * @param {boolean} [show] Show anchor, omit to toggle
5024 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
5025 show
= show
=== undefined ? !this.anchored
: !!show
;
5027 if ( this.anchored
!== show
) {
5029 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
5030 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5032 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
5033 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5035 this.anchored
= show
;
5039 * Change which edge the anchor appears on.
5041 * @param {string} edge 'top', 'bottom', 'start' or 'end'
5043 OO
.ui
.PopupWidget
.prototype.setAnchorEdge = function ( edge
) {
5044 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge
) === -1 ) {
5045 throw new Error( 'Invalid value for edge: ' + edge
);
5047 if ( this.anchorEdge
!== null ) {
5048 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5050 this.anchorEdge
= edge
;
5051 if ( this.anchored
) {
5052 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + edge
);
5057 * Check if the anchor is visible.
5059 * @return {boolean} Anchor is visible
5061 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
5062 return this.anchored
;
5066 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
5067 * `.toggle( true )` after its #$element is attached to the DOM.
5069 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5070 * it in the right place and with the right dimensions only work correctly while it is attached.
5071 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5072 * strictly enforced, so currently it only generates a warning in the browser console.
5077 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
5079 show
= show
=== undefined ? !this.isVisible() : !!show
;
5081 change
= show
!== this.isVisible();
5083 if ( show
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
5084 OO
.ui
.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5085 this.warnedUnattached
= true;
5087 if ( show
&& !this.$floatableContainer
&& this.isElementAttached() ) {
5088 // Fall back to the parent node if the floatableContainer is not set
5089 this.setFloatableContainer( this.$element
.parent() );
5093 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
5096 this.togglePositioning( show
&& !!this.$floatableContainer
);
5099 if ( this.autoClose
) {
5100 this.bindMouseDownListener();
5101 this.bindKeyDownListener();
5103 this.updateDimensions();
5104 this.toggleClipping( true );
5105 this.emit( 'ready' );
5107 this.toggleClipping( false );
5108 if ( this.autoClose
) {
5109 this.unbindMouseDownListener();
5110 this.unbindKeyDownListener();
5119 * Set the size of the popup.
5121 * Changing the size may also change the popup's position depending on the alignment.
5123 * @param {number} width Width in pixels
5124 * @param {number} height Height in pixels
5125 * @param {boolean} [transition=false] Use a smooth transition
5128 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
5130 this.height
= height
!== undefined ? height
: null;
5131 if ( this.isVisible() ) {
5132 this.updateDimensions( transition
);
5137 * Update the size and position.
5139 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5140 * be called automatically.
5142 * @param {boolean} [transition=false] Use a smooth transition
5145 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
5148 // Prevent transition from being interrupted
5149 clearTimeout( this.transitionTimeout
);
5151 // Enable transition
5152 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
5158 // Prevent transitioning after transition is complete
5159 this.transitionTimeout
= setTimeout( function () {
5160 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5163 // Prevent transitioning immediately
5164 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5171 OO
.ui
.PopupWidget
.prototype.computePosition = function () {
5172 var direction
, align
, vertical
, start
, end
, near
, far
, sizeProp
, popupSize
, anchorSize
, anchorPos
,
5173 anchorOffset
, anchorMargin
, parentPosition
, positionProp
, positionAdjustment
, floatablePos
,
5174 offsetParentPos
, containerPos
,
5176 anchorCss
= { left
: '', right
: '', top
: '', bottom
: '' },
5179 'force-left': 'backwards',
5180 'force-right': 'forwards'
5183 'force-left': 'forwards',
5184 'force-right': 'backwards'
5204 if ( !this.$container
) {
5205 // Lazy-initialize $container if not specified in constructor
5206 this.$container
= $( this.getClosestScrollableElementContainer() );
5208 direction
= this.$container
.css( 'direction' );
5210 // Set height and width before we do anything else, since it might cause our measurements
5211 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5214 height
: this.height
!== null ? this.height
: 'auto'
5217 align
= alignMap
[ direction
][ this.align
] || this.align
;
5218 // If the popup is positioned before or after, then the anchor positioning is vertical, otherwise horizontal
5219 vertical
= this.popupPosition
=== 'before' || this.popupPosition
=== 'after';
5220 start
= vertical
? 'top' : ( direction
=== 'rtl' ? 'right' : 'left' );
5221 end
= vertical
? 'bottom' : ( direction
=== 'rtl' ? 'left' : 'right' );
5222 near
= vertical
? 'top' : 'left';
5223 far
= vertical
? 'bottom' : 'right';
5224 sizeProp
= vertical
? 'Height' : 'Width';
5225 popupSize
= vertical
? ( this.height
|| this.$popup
.height() ) : this.width
;
5227 this.setAnchorEdge( anchorEdgeMap
[ this.popupPosition
] );
5228 this.horizontalPosition
= vertical
? this.popupPosition
: hPosMap
[ align
];
5229 this.verticalPosition
= vertical
? vPosMap
[ align
] : this.popupPosition
;
5232 parentPosition
= OO
.ui
.mixin
.FloatableElement
.prototype.computePosition
.call( this );
5233 // Find out which property FloatableElement used for positioning, and adjust that value
5234 positionProp
= vertical
?
5235 ( parentPosition
.top
!== '' ? 'top' : 'bottom' ) :
5236 ( parentPosition
.left
!== '' ? 'left' : 'right' );
5238 // Figure out where the near and far edges of the popup and $floatableContainer are
5239 floatablePos
= this.$floatableContainer
.offset();
5240 floatablePos
[ far
] = floatablePos
[ near
] + this.$floatableContainer
[ 'outer' + sizeProp
]();
5241 // Measure where the offsetParent is and compute our position based on that and parentPosition
5242 offsetParentPos
= this.$element
.offsetParent().offset();
5244 if ( positionProp
=== near
) {
5245 popupPos
[ near
] = offsetParentPos
[ near
] + parentPosition
[ near
];
5246 popupPos
[ far
] = popupPos
[ near
] + popupSize
;
5248 popupPos
[ far
] = offsetParentPos
[ near
] +
5249 this.$element
.offsetParent()[ 'inner' + sizeProp
]() - parentPosition
[ far
];
5250 popupPos
[ near
] = popupPos
[ far
] - popupSize
;
5253 // Position the anchor (which is positioned relative to the popup) to point to $floatableContainer
5254 anchorPos
= ( floatablePos
[ start
] + floatablePos
[ end
] ) / 2;
5255 anchorOffset
= ( start
=== far
? -1 : 1 ) * ( anchorPos
- popupPos
[ start
] );
5257 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more space
5258 // this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use scrollWidth/Height
5259 anchorSize
= this.$anchor
[ 0 ][ 'scroll' + sizeProp
];
5260 anchorMargin
= parseFloat( this.$anchor
.css( 'margin-' + start
) );
5261 if ( anchorOffset
+ anchorMargin
< 2 * anchorSize
) {
5262 // Not enough space for the anchor on the start side; pull the popup startwards
5263 positionAdjustment
= ( positionProp
=== start
? -1 : 1 ) *
5264 ( 2 * anchorSize
- ( anchorOffset
+ anchorMargin
) );
5265 } else if ( anchorOffset
+ anchorMargin
> popupSize
- 2 * anchorSize
) {
5266 // Not enough space for the anchor on the end side; pull the popup endwards
5267 positionAdjustment
= ( positionProp
=== end
? -1 : 1 ) *
5268 ( anchorOffset
+ anchorMargin
- ( popupSize
- 2 * anchorSize
) );
5270 positionAdjustment
= 0;
5273 // Check if the popup will go beyond the edge of this.$container
5274 containerPos
= this.$container
.offset();
5275 containerPos
[ far
] = containerPos
[ near
] + this.$container
[ 'inner' + sizeProp
]();
5276 // Take into account how much the popup will move because of the adjustments we're going to make
5277 popupPos
[ near
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5278 popupPos
[ far
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5279 if ( containerPos
[ near
] + this.containerPadding
> popupPos
[ near
] ) {
5280 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5281 positionAdjustment
+= ( positionProp
=== near
? 1 : -1 ) *
5282 ( containerPos
[ near
] + this.containerPadding
- popupPos
[ near
] );
5283 } else if ( containerPos
[ far
] - this.containerPadding
< popupPos
[ far
] ) {
5284 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5285 positionAdjustment
+= ( positionProp
=== far
? 1 : -1 ) *
5286 ( popupPos
[ far
] - ( containerPos
[ far
] - this.containerPadding
) );
5289 // Adjust anchorOffset for positionAdjustment
5290 anchorOffset
+= ( positionProp
=== start
? -1 : 1 ) * positionAdjustment
;
5292 // Position the anchor
5293 anchorCss
[ start
] = anchorOffset
;
5294 this.$anchor
.css( anchorCss
);
5295 // Move the popup if needed
5296 parentPosition
[ positionProp
] += positionAdjustment
;
5298 return parentPosition
;
5302 * Set popup alignment
5304 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5305 * `backwards` or `forwards`.
5307 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
5308 // Validate alignment
5309 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
5312 this.align
= 'center';
5318 * Get popup alignment
5320 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5321 * `backwards` or `forwards`.
5323 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
5328 * Change the positioning of the popup.
5330 * @param {string} position 'above', 'below', 'before' or 'after'
5332 OO
.ui
.PopupWidget
.prototype.setPosition = function ( position
) {
5333 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position
) === -1 ) {
5336 this.popupPosition
= position
;
5341 * Get popup positioning.
5343 * @return {string} 'above', 'below', 'before' or 'after'
5345 OO
.ui
.PopupWidget
.prototype.getPosition = function () {
5346 return this.popupPosition
;
5350 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5351 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5352 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5353 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5359 * @param {Object} [config] Configuration options
5360 * @cfg {Object} [popup] Configuration to pass to popup
5361 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5363 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
5364 // Configuration initialization
5365 config
= config
|| {};
5368 this.popup
= new OO
.ui
.PopupWidget( $.extend(
5371 $floatableContainer
: this.$element
5375 $autoCloseIgnore
: this.$element
.add( config
.popup
&& config
.popup
.$autoCloseIgnore
)
5385 * @return {OO.ui.PopupWidget} Popup widget
5387 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
5392 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5393 * which is used to display additional information or options.
5396 * // Example of a popup button.
5397 * var popupButton = new OO.ui.PopupButtonWidget( {
5398 * label: 'Popup button with options',
5401 * $content: $( '<p>Additional options here.</p>' ),
5403 * align: 'force-left'
5406 * // Append the button to the DOM.
5407 * $( 'body' ).append( popupButton.$element );
5410 * @extends OO.ui.ButtonWidget
5411 * @mixins OO.ui.mixin.PopupElement
5414 * @param {Object} [config] Configuration options
5415 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
5416 * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
5417 * containing `<div>` and has a larger area. By default, the popup uses relative positioning.
5418 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
5420 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
5421 // Parent constructor
5422 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
5424 // Mixin constructors
5425 OO
.ui
.mixin
.PopupElement
.call( this, config
);
5428 this.$overlay
= config
.$overlay
|| this.$element
;
5431 this.connect( this, { click
: 'onAction' } );
5435 .addClass( 'oo-ui-popupButtonWidget' )
5436 .attr( 'aria-haspopup', 'true' );
5438 .addClass( 'oo-ui-popupButtonWidget-popup' )
5439 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
5440 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
5441 this.$overlay
.append( this.popup
.$element
);
5446 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
5447 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
5452 * Handle the button action being triggered.
5456 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
5457 this.popup
.toggle();
5461 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
5463 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
5468 * @mixins OO.ui.mixin.GroupElement
5471 * @param {Object} [config] Configuration options
5473 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
5474 // Mixin constructors
5475 OO
.ui
.mixin
.GroupElement
.call( this, config
);
5480 OO
.mixinClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
5485 * Set the disabled state of the widget.
5487 * This will also update the disabled state of child widgets.
5489 * @param {boolean} disabled Disable widget
5492 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
5496 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
5497 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
5499 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
5501 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5502 this.items
[ i
].updateDisabled();
5510 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
5512 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
5513 * allows bidirectional communication.
5515 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
5523 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
5530 * Check if widget is disabled.
5532 * Checks parent if present, making disabled state inheritable.
5534 * @return {boolean} Widget is disabled
5536 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
5537 return this.disabled
||
5538 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
5542 * Set group element is in.
5544 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
5547 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
5549 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
5550 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
5552 // Initialize item disabled states
5553 this.updateDisabled();
5559 * OptionWidgets are special elements that can be selected and configured with data. The
5560 * data is often unique for each option, but it does not have to be. OptionWidgets are used
5561 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
5562 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
5564 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5567 * @extends OO.ui.Widget
5568 * @mixins OO.ui.mixin.ItemWidget
5569 * @mixins OO.ui.mixin.LabelElement
5570 * @mixins OO.ui.mixin.FlaggedElement
5571 * @mixins OO.ui.mixin.AccessKeyedElement
5574 * @param {Object} [config] Configuration options
5576 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
5577 // Configuration initialization
5578 config
= config
|| {};
5580 // Parent constructor
5581 OO
.ui
.OptionWidget
.parent
.call( this, config
);
5583 // Mixin constructors
5584 OO
.ui
.mixin
.ItemWidget
.call( this );
5585 OO
.ui
.mixin
.LabelElement
.call( this, config
);
5586 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
5587 OO
.ui
.mixin
.AccessKeyedElement
.call( this, config
);
5590 this.selected
= false;
5591 this.highlighted
= false;
5592 this.pressed
= false;
5596 .data( 'oo-ui-optionWidget', this )
5597 // Allow programmatic focussing (and by accesskey), but not tabbing
5598 .attr( 'tabindex', '-1' )
5599 .attr( 'role', 'option' )
5600 .attr( 'aria-selected', 'false' )
5601 .addClass( 'oo-ui-optionWidget' )
5602 .append( this.$label
);
5607 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
5608 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
5609 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
5610 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
5611 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
5613 /* Static Properties */
5616 * Whether this option can be selected. See #setSelected.
5620 * @property {boolean}
5622 OO
.ui
.OptionWidget
.static.selectable
= true;
5625 * Whether this option can be highlighted. See #setHighlighted.
5629 * @property {boolean}
5631 OO
.ui
.OptionWidget
.static.highlightable
= true;
5634 * Whether this option can be pressed. See #setPressed.
5638 * @property {boolean}
5640 OO
.ui
.OptionWidget
.static.pressable
= true;
5643 * Whether this option will be scrolled into view when it is selected.
5647 * @property {boolean}
5649 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
5654 * Check if the option can be selected.
5656 * @return {boolean} Item is selectable
5658 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
5659 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
5663 * Check if the option can be highlighted. A highlight indicates that the option
5664 * may be selected when a user presses enter or clicks. Disabled items cannot
5667 * @return {boolean} Item is highlightable
5669 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
5670 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
5674 * Check if the option can be pressed. The pressed state occurs when a user mouses
5675 * down on an item, but has not yet let go of the mouse.
5677 * @return {boolean} Item is pressable
5679 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
5680 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
5684 * Check if the option is selected.
5686 * @return {boolean} Item is selected
5688 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
5689 return this.selected
;
5693 * Check if the option is highlighted. A highlight indicates that the
5694 * item may be selected when a user presses enter or clicks.
5696 * @return {boolean} Item is highlighted
5698 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
5699 return this.highlighted
;
5703 * Check if the option is pressed. The pressed state occurs when a user mouses
5704 * down on an item, but has not yet let go of the mouse. The item may appear
5705 * selected, but it will not be selected until the user releases the mouse.
5707 * @return {boolean} Item is pressed
5709 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
5710 return this.pressed
;
5714 * Set the option’s selected state. In general, all modifications to the selection
5715 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
5716 * method instead of this method.
5718 * @param {boolean} [state=false] Select option
5721 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
5722 if ( this.constructor.static.selectable
) {
5723 this.selected
= !!state
;
5725 .toggleClass( 'oo-ui-optionWidget-selected', state
)
5726 .attr( 'aria-selected', state
.toString() );
5727 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
5728 this.scrollElementIntoView();
5730 this.updateThemeClasses();
5736 * Set the option’s highlighted state. In general, all programmatic
5737 * modifications to the highlight should be handled by the
5738 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
5739 * method instead of this method.
5741 * @param {boolean} [state=false] Highlight option
5744 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
5745 if ( this.constructor.static.highlightable
) {
5746 this.highlighted
= !!state
;
5747 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
5748 this.updateThemeClasses();
5754 * Set the option’s pressed state. In general, all
5755 * programmatic modifications to the pressed state should be handled by the
5756 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
5757 * method instead of this method.
5759 * @param {boolean} [state=false] Press option
5762 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
5763 if ( this.constructor.static.pressable
) {
5764 this.pressed
= !!state
;
5765 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
5766 this.updateThemeClasses();
5772 * Get text to match search strings against.
5774 * The default implementation returns the label text, but subclasses
5775 * can override this to provide more complex behavior.
5777 * @return {string|boolean} String to match search string against
5779 OO
.ui
.OptionWidget
.prototype.getMatchText = function () {
5780 var label
= this.getLabel();
5781 return typeof label
=== 'string' ? label
: this.$label
.text();
5785 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
5786 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
5787 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
5790 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
5791 * information, please see the [OOjs UI documentation on MediaWiki][1].
5794 * // Example of a select widget with three options
5795 * var select = new OO.ui.SelectWidget( {
5797 * new OO.ui.OptionWidget( {
5799 * label: 'Option One',
5801 * new OO.ui.OptionWidget( {
5803 * label: 'Option Two',
5805 * new OO.ui.OptionWidget( {
5807 * label: 'Option Three',
5811 * $( 'body' ).append( select.$element );
5813 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5817 * @extends OO.ui.Widget
5818 * @mixins OO.ui.mixin.GroupWidget
5821 * @param {Object} [config] Configuration options
5822 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
5823 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
5824 * the [OOjs UI documentation on MediaWiki] [2] for examples.
5825 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5827 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
5828 // Configuration initialization
5829 config
= config
|| {};
5831 // Parent constructor
5832 OO
.ui
.SelectWidget
.parent
.call( this, config
);
5834 // Mixin constructors
5835 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
5838 this.pressed
= false;
5839 this.selecting
= null;
5840 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
5841 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
5842 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
5843 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
5844 this.keyPressBuffer
= '';
5845 this.keyPressBufferTimer
= null;
5846 this.blockMouseOverEvents
= 0;
5849 this.connect( this, {
5853 focusin
: this.onFocus
.bind( this ),
5854 mousedown
: this.onMouseDown
.bind( this ),
5855 mouseover
: this.onMouseOver
.bind( this ),
5856 mouseleave
: this.onMouseLeave
.bind( this )
5861 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
5862 .attr( 'role', 'listbox' );
5863 this.setFocusOwner( this.$element
);
5864 if ( Array
.isArray( config
.items
) ) {
5865 this.addItems( config
.items
);
5871 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
5872 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
5879 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
5881 * @param {OO.ui.OptionWidget|null} item Highlighted item
5887 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
5888 * pressed state of an option.
5890 * @param {OO.ui.OptionWidget|null} item Pressed item
5896 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
5898 * @param {OO.ui.OptionWidget|null} item Selected item
5903 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
5904 * @param {OO.ui.OptionWidget} item Chosen item
5910 * An `add` event is emitted when options are added to the select with the #addItems method.
5912 * @param {OO.ui.OptionWidget[]} items Added items
5913 * @param {number} index Index of insertion point
5919 * A `remove` event is emitted when options are removed from the select with the #clearItems
5920 * or #removeItems methods.
5922 * @param {OO.ui.OptionWidget[]} items Removed items
5928 * Handle focus events
5931 * @param {jQuery.Event} event
5933 OO
.ui
.SelectWidget
.prototype.onFocus = function ( event
) {
5935 if ( event
.target
=== this.$element
[ 0 ] ) {
5936 // This widget was focussed, e.g. by the user tabbing to it.
5937 // The styles for focus state depend on one of the items being selected.
5938 if ( !this.getSelectedItem() ) {
5939 item
= this.getFirstSelectableItem();
5942 // One of the options got focussed (and the event bubbled up here).
5943 // They can't be tabbed to, but they can be activated using accesskeys.
5944 item
= this.getTargetItem( event
);
5948 if ( item
.constructor.static.highlightable
) {
5949 this.highlightItem( item
);
5951 this.selectItem( item
);
5955 if ( event
.target
!== this.$element
[ 0 ] ) {
5956 this.$focusOwner
.focus();
5961 * Handle mouse down events.
5964 * @param {jQuery.Event} e Mouse down event
5966 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
5969 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
5970 this.togglePressed( true );
5971 item
= this.getTargetItem( e
);
5972 if ( item
&& item
.isSelectable() ) {
5973 this.pressItem( item
);
5974 this.selecting
= item
;
5975 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
5976 this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler
, true );
5983 * Handle mouse up events.
5986 * @param {MouseEvent} e Mouse up event
5988 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
5991 this.togglePressed( false );
5992 if ( !this.selecting
) {
5993 item
= this.getTargetItem( e
);
5994 if ( item
&& item
.isSelectable() ) {
5995 this.selecting
= item
;
5998 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
5999 this.pressItem( null );
6000 this.chooseItem( this.selecting
);
6001 this.selecting
= null;
6004 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
6005 this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler
, true );
6011 * Handle mouse move events.
6014 * @param {MouseEvent} e Mouse move event
6016 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
6019 if ( !this.isDisabled() && this.pressed
) {
6020 item
= this.getTargetItem( e
);
6021 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
6022 this.pressItem( item
);
6023 this.selecting
= item
;
6029 * Handle mouse over events.
6032 * @param {jQuery.Event} e Mouse over event
6034 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
6036 if ( this.blockMouseOverEvents
) {
6039 if ( !this.isDisabled() ) {
6040 item
= this.getTargetItem( e
);
6041 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
6047 * Handle mouse leave events.
6050 * @param {jQuery.Event} e Mouse over event
6052 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
6053 if ( !this.isDisabled() ) {
6054 this.highlightItem( null );
6060 * Handle key down events.
6063 * @param {KeyboardEvent} e Key down event
6065 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
6068 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
6070 if ( !this.isDisabled() && this.isVisible() ) {
6071 switch ( e
.keyCode
) {
6072 case OO
.ui
.Keys
.ENTER
:
6073 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6074 // Was only highlighted, now let's select it. No-op if already selected.
6075 this.chooseItem( currentItem
);
6080 case OO
.ui
.Keys
.LEFT
:
6081 this.clearKeyPressBuffer();
6082 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
6085 case OO
.ui
.Keys
.DOWN
:
6086 case OO
.ui
.Keys
.RIGHT
:
6087 this.clearKeyPressBuffer();
6088 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
6091 case OO
.ui
.Keys
.ESCAPE
:
6092 case OO
.ui
.Keys
.TAB
:
6093 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6094 currentItem
.setHighlighted( false );
6096 this.unbindKeyDownListener();
6097 this.unbindKeyPressListener();
6098 // Don't prevent tabbing away / defocusing
6104 if ( nextItem
.constructor.static.highlightable
) {
6105 this.highlightItem( nextItem
);
6107 this.chooseItem( nextItem
);
6109 this.scrollItemIntoView( nextItem
);
6114 e
.stopPropagation();
6120 * Bind key down listener.
6124 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
6125 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
6129 * Unbind key down listener.
6133 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
6134 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
6138 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6140 * @param {OO.ui.OptionWidget} item Item to scroll into view
6142 OO
.ui
.SelectWidget
.prototype.scrollItemIntoView = function ( item
) {
6144 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
6145 // and around 100-150 ms after it is finished.
6146 this.blockMouseOverEvents
++;
6147 item
.scrollElementIntoView().done( function () {
6148 setTimeout( function () {
6149 widget
.blockMouseOverEvents
--;
6155 * Clear the key-press buffer
6159 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
6160 if ( this.keyPressBufferTimer
) {
6161 clearTimeout( this.keyPressBufferTimer
);
6162 this.keyPressBufferTimer
= null;
6164 this.keyPressBuffer
= '';
6168 * Handle key press events.
6171 * @param {KeyboardEvent} e Key press event
6173 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
6174 var c
, filter
, item
;
6176 if ( !e
.charCode
) {
6177 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
6178 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
6183 if ( String
.fromCodePoint
) {
6184 c
= String
.fromCodePoint( e
.charCode
);
6186 c
= String
.fromCharCode( e
.charCode
);
6189 if ( this.keyPressBufferTimer
) {
6190 clearTimeout( this.keyPressBufferTimer
);
6192 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
6194 item
= this.getHighlightedItem() || this.getSelectedItem();
6196 if ( this.keyPressBuffer
=== c
) {
6197 // Common (if weird) special case: typing "xxxx" will cycle through all
6198 // the items beginning with "x".
6200 item
= this.getRelativeSelectableItem( item
, 1 );
6203 this.keyPressBuffer
+= c
;
6206 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
6207 if ( !item
|| !filter( item
) ) {
6208 item
= this.getRelativeSelectableItem( item
, 1, filter
);
6211 if ( this.isVisible() && item
.constructor.static.highlightable
) {
6212 this.highlightItem( item
);
6214 this.chooseItem( item
);
6216 this.scrollItemIntoView( item
);
6220 e
.stopPropagation();
6224 * Get a matcher for the specific string
6227 * @param {string} s String to match against items
6228 * @param {boolean} [exact=false] Only accept exact matches
6229 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6231 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
6234 if ( s
.normalize
) {
6237 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
6238 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
6242 re
= new RegExp( re
, 'i' );
6243 return function ( item
) {
6244 var matchText
= item
.getMatchText();
6245 if ( matchText
.normalize
) {
6246 matchText
= matchText
.normalize();
6248 return re
.test( matchText
);
6253 * Bind key press listener.
6257 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
6258 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler
, true );
6262 * Unbind key down listener.
6264 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6269 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
6270 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler
, true );
6271 this.clearKeyPressBuffer();
6275 * Visibility change handler
6278 * @param {boolean} visible
6280 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
6282 this.clearKeyPressBuffer();
6287 * Get the closest item to a jQuery.Event.
6290 * @param {jQuery.Event} e
6291 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6293 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
6294 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
6298 * Get selected item.
6300 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6302 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
6305 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6306 if ( this.items
[ i
].isSelected() ) {
6307 return this.items
[ i
];
6314 * Get highlighted item.
6316 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6318 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
6321 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6322 if ( this.items
[ i
].isHighlighted() ) {
6323 return this.items
[ i
];
6330 * Toggle pressed state.
6332 * Press is a state that occurs when a user mouses down on an item, but
6333 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
6334 * until the user releases the mouse.
6336 * @param {boolean} pressed An option is being pressed
6338 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
6339 if ( pressed
=== undefined ) {
6340 pressed
= !this.pressed
;
6342 if ( pressed
!== this.pressed
) {
6344 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
6345 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
6346 this.pressed
= pressed
;
6351 * Highlight an option. If the `item` param is omitted, no options will be highlighted
6352 * and any existing highlight will be removed. The highlight is mutually exclusive.
6354 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
6358 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
6359 var i
, len
, highlighted
,
6362 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6363 highlighted
= this.items
[ i
] === item
;
6364 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
6365 this.items
[ i
].setHighlighted( highlighted
);
6371 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
6373 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
6375 this.emit( 'highlight', item
);
6382 * Fetch an item by its label.
6384 * @param {string} label Label of the item to select.
6385 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6386 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
6388 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
6390 len
= this.items
.length
,
6391 filter
= this.getItemMatcher( label
, true );
6393 for ( i
= 0; i
< len
; i
++ ) {
6394 item
= this.items
[ i
];
6395 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
6402 filter
= this.getItemMatcher( label
, false );
6403 for ( i
= 0; i
< len
; i
++ ) {
6404 item
= this.items
[ i
];
6405 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
6421 * Programmatically select an option by its label. If the item does not exist,
6422 * all options will be deselected.
6424 * @param {string} [label] Label of the item to select.
6425 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6429 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
6430 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
6431 if ( label
=== undefined || !itemFromLabel
) {
6432 return this.selectItem();
6434 return this.selectItem( itemFromLabel
);
6438 * Programmatically select an option by its data. If the `data` parameter is omitted,
6439 * or if the item does not exist, all options will be deselected.
6441 * @param {Object|string} [data] Value of the item to select, omit to deselect all
6445 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
6446 var itemFromData
= this.getItemFromData( data
);
6447 if ( data
=== undefined || !itemFromData
) {
6448 return this.selectItem();
6450 return this.selectItem( itemFromData
);
6454 * Programmatically select an option by its reference. If the `item` parameter is omitted,
6455 * all options will be deselected.
6457 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
6461 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
6462 var i
, len
, selected
,
6465 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6466 selected
= this.items
[ i
] === item
;
6467 if ( this.items
[ i
].isSelected() !== selected
) {
6468 this.items
[ i
].setSelected( selected
);
6473 if ( item
&& !item
.constructor.static.highlightable
) {
6475 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
6477 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
6480 this.emit( 'select', item
);
6489 * Press is a state that occurs when a user mouses down on an item, but has not
6490 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
6491 * releases the mouse.
6493 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
6497 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
6498 var i
, len
, pressed
,
6501 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6502 pressed
= this.items
[ i
] === item
;
6503 if ( this.items
[ i
].isPressed() !== pressed
) {
6504 this.items
[ i
].setPressed( pressed
);
6509 this.emit( 'press', item
);
6518 * Note that ‘choose’ should never be modified programmatically. A user can choose
6519 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
6520 * use the #selectItem method.
6522 * This method is identical to #selectItem, but may vary in subclasses that take additional action
6523 * when users choose an item with the keyboard or mouse.
6525 * @param {OO.ui.OptionWidget} item Item to choose
6529 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
6531 this.selectItem( item
);
6532 this.emit( 'choose', item
);
6539 * Get an option by its position relative to the specified item (or to the start of the option array,
6540 * if item is `null`). The direction in which to search through the option array is specified with a
6541 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
6542 * `null` if there are no options in the array.
6544 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
6545 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
6546 * @param {Function} [filter] Only consider items for which this function returns
6547 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
6548 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
6550 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
6551 var currentIndex
, nextIndex
, i
,
6552 increase
= direction
> 0 ? 1 : -1,
6553 len
= this.items
.length
;
6555 if ( item
instanceof OO
.ui
.OptionWidget
) {
6556 currentIndex
= this.items
.indexOf( item
);
6557 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
6559 // If no item is selected and moving forward, start at the beginning.
6560 // If moving backward, start at the end.
6561 nextIndex
= direction
> 0 ? 0 : len
- 1;
6564 for ( i
= 0; i
< len
; i
++ ) {
6565 item
= this.items
[ nextIndex
];
6567 item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() &&
6568 ( !filter
|| filter( item
) )
6572 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
6578 * Get the next selectable item or `null` if there are no selectable items.
6579 * Disabled options and menu-section markers and breaks are not selectable.
6581 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
6583 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
6584 return this.getRelativeSelectableItem( null, 1 );
6588 * Add an array of options to the select. Optionally, an index number can be used to
6589 * specify an insertion point.
6591 * @param {OO.ui.OptionWidget[]} items Items to add
6592 * @param {number} [index] Index to insert items after
6596 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
6598 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
6600 // Always provide an index, even if it was omitted
6601 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
6607 * Remove the specified array of options from the select. Options will be detached
6608 * from the DOM, not removed, so they can be reused later. To remove all options from
6609 * the select, you may wish to use the #clearItems method instead.
6611 * @param {OO.ui.OptionWidget[]} items Items to remove
6615 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
6618 // Deselect items being removed
6619 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
6621 if ( item
.isSelected() ) {
6622 this.selectItem( null );
6627 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
6629 this.emit( 'remove', items
);
6635 * Clear all options from the select. Options will be detached from the DOM, not removed,
6636 * so that they can be reused later. To remove a subset of options from the select, use
6637 * the #removeItems method.
6642 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
6643 var items
= this.items
.slice();
6646 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
6649 this.selectItem( null );
6651 this.emit( 'remove', items
);
6657 * Set the DOM element which has focus while the user is interacting with this SelectWidget.
6659 * Currently this is just used to set `aria-activedescendant` on it.
6662 * @param {jQuery} $focusOwner
6664 OO
.ui
.SelectWidget
.prototype.setFocusOwner = function ( $focusOwner
) {
6665 this.$focusOwner
= $focusOwner
;
6669 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
6670 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
6671 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
6672 * options. For more information about options and selects, please see the
6673 * [OOjs UI documentation on MediaWiki][1].
6676 * // Decorated options in a select widget
6677 * var select = new OO.ui.SelectWidget( {
6679 * new OO.ui.DecoratedOptionWidget( {
6681 * label: 'Option with icon',
6684 * new OO.ui.DecoratedOptionWidget( {
6686 * label: 'Option with indicator',
6691 * $( 'body' ).append( select.$element );
6693 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6696 * @extends OO.ui.OptionWidget
6697 * @mixins OO.ui.mixin.IconElement
6698 * @mixins OO.ui.mixin.IndicatorElement
6701 * @param {Object} [config] Configuration options
6703 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
6704 // Parent constructor
6705 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
6707 // Mixin constructors
6708 OO
.ui
.mixin
.IconElement
.call( this, config
);
6709 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
6713 .addClass( 'oo-ui-decoratedOptionWidget' )
6714 .prepend( this.$icon
)
6715 .append( this.$indicator
);
6720 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
6721 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
6722 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
6725 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
6726 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
6727 * the [OOjs UI documentation on MediaWiki] [1] for more information.
6729 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
6732 * @extends OO.ui.DecoratedOptionWidget
6735 * @param {Object} [config] Configuration options
6737 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
6738 // Parent constructor
6739 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
6742 this.$element
.addClass( 'oo-ui-menuOptionWidget' );
6747 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
6749 /* Static Properties */
6755 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
6758 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
6759 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
6762 * var myDropdown = new OO.ui.DropdownWidget( {
6765 * new OO.ui.MenuSectionOptionWidget( {
6768 * new OO.ui.MenuOptionWidget( {
6770 * label: 'Welsh Corgi'
6772 * new OO.ui.MenuOptionWidget( {
6774 * label: 'Standard Poodle'
6776 * new OO.ui.MenuSectionOptionWidget( {
6779 * new OO.ui.MenuOptionWidget( {
6786 * $( 'body' ).append( myDropdown.$element );
6789 * @extends OO.ui.DecoratedOptionWidget
6792 * @param {Object} [config] Configuration options
6794 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
6795 // Parent constructor
6796 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
6799 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' )
6800 .removeAttr( 'role aria-selected' );
6805 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
6807 /* Static Properties */
6813 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
6819 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
6822 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
6823 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
6824 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
6825 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
6826 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
6827 * and customized to be opened, closed, and displayed as needed.
6829 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
6830 * mouse outside the menu.
6832 * Menus also have support for keyboard interaction:
6834 * - Enter/Return key: choose and select a menu option
6835 * - Up-arrow key: highlight the previous menu option
6836 * - Down-arrow key: highlight the next menu option
6837 * - Esc key: hide the menu
6839 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
6841 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6842 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6845 * @extends OO.ui.SelectWidget
6846 * @mixins OO.ui.mixin.ClippableElement
6847 * @mixins OO.ui.mixin.FloatableElement
6850 * @param {Object} [config] Configuration options
6851 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
6852 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
6853 * and {@link OO.ui.mixin.LookupElement LookupElement}
6854 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
6855 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiselectWidget CapsuleMultiselectWidget}
6856 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
6857 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
6858 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
6859 * that button, unless the button (or its parent widget) is passed in here.
6860 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
6861 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
6862 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
6863 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
6864 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
6865 * @cfg {number} [width] Width of the menu
6867 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
6868 // Configuration initialization
6869 config
= config
|| {};
6871 // Parent constructor
6872 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
6874 // Mixin constructors
6875 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
6876 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
6879 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
6880 this.hideOnChoose
= config
.hideOnChoose
=== undefined || !!config
.hideOnChoose
;
6881 this.filterFromInput
= !!config
.filterFromInput
;
6882 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
6883 this.$widget
= config
.widget
? config
.widget
.$element
: null;
6884 this.$autoCloseIgnore
= config
.$autoCloseIgnore
|| $( [] );
6885 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
6886 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
6887 this.highlightOnFilter
= !!config
.highlightOnFilter
;
6888 this.width
= config
.width
;
6891 this.$element
.addClass( 'oo-ui-menuSelectWidget' );
6892 if ( config
.widget
) {
6893 this.setFocusOwner( config
.widget
.$tabIndexed
);
6896 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
6897 // that reference properties not initialized at that time of parent class construction
6898 // TODO: Find a better way to handle post-constructor setup
6899 this.visible
= false;
6900 this.$element
.addClass( 'oo-ui-element-hidden' );
6905 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
6906 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
6907 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
6914 * The menu is ready: it is visible and has been positioned and clipped.
6920 * Handles document mouse down events.
6923 * @param {MouseEvent} e Mouse down event
6925 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
6929 this.$element
.add( this.$widget
).add( this.$autoCloseIgnore
).get(),
6934 this.toggle( false );
6941 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
6942 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
6944 if ( !this.isDisabled() && this.isVisible() ) {
6945 switch ( e
.keyCode
) {
6946 case OO
.ui
.Keys
.LEFT
:
6947 case OO
.ui
.Keys
.RIGHT
:
6948 // Do nothing if a text field is associated, arrow keys will be handled natively
6949 if ( !this.$input
) {
6950 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
6953 case OO
.ui
.Keys
.ESCAPE
:
6954 case OO
.ui
.Keys
.TAB
:
6955 if ( currentItem
) {
6956 currentItem
.setHighlighted( false );
6958 this.toggle( false );
6959 // Don't prevent tabbing away, prevent defocusing
6960 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
6962 e
.stopPropagation();
6966 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
6973 * Update menu item visibility after input changes.
6977 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
6978 var i
, item
, visible
, section
, sectionEmpty
,
6979 firstItemFound
= false,
6981 len
= this.items
.length
,
6982 showAll
= !this.isVisible(),
6983 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() ),
6984 exactFilter
= this.getItemMatcher( this.$input
.val(), true ),
6987 // Hide non-matching options, and also hide section headers if all options
6988 // in their section are hidden.
6989 for ( i
= 0; i
< len
; i
++ ) {
6990 item
= this.items
[ i
];
6991 if ( item
instanceof OO
.ui
.MenuSectionOptionWidget
) {
6993 // If the previous section was empty, hide its header
6994 section
.toggle( showAll
|| !sectionEmpty
);
6997 sectionEmpty
= true;
6998 } else if ( item
instanceof OO
.ui
.OptionWidget
) {
6999 visible
= showAll
|| filter( item
);
7000 exactMatch
= exactMatch
|| exactFilter( item
);
7001 anyVisible
= anyVisible
|| visible
;
7002 sectionEmpty
= sectionEmpty
&& !visible
;
7003 item
.toggle( visible
);
7004 if ( this.highlightOnFilter
&& visible
&& !firstItemFound
) {
7005 // Highlight the first item in the list
7006 this.highlightItem( item
);
7007 firstItemFound
= true;
7011 // Process the final section
7013 section
.toggle( showAll
|| !sectionEmpty
);
7016 if ( anyVisible
&& this.items
.length
&& !exactMatch
) {
7017 this.scrollItemIntoView( this.items
[ 0 ] );
7020 this.$element
.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible
);
7022 // Reevaluate clipping
7029 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
7030 if ( this.$input
) {
7031 this.$input
.on( 'keydown', this.onKeyDownHandler
);
7033 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
7040 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
7041 if ( this.$input
) {
7042 this.$input
.off( 'keydown', this.onKeyDownHandler
);
7044 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
7051 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
7052 if ( this.$input
) {
7053 if ( this.filterFromInput
) {
7054 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
7055 this.updateItemVisibility();
7058 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
7065 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
7066 if ( this.$input
) {
7067 if ( this.filterFromInput
) {
7068 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
7069 this.updateItemVisibility();
7072 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
7079 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
7081 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
7082 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
7084 * @param {OO.ui.OptionWidget} item Item to choose
7087 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
7088 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
7089 if ( this.hideOnChoose
) {
7090 this.toggle( false );
7098 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
7100 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
7102 // Reevaluate clipping
7111 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
7113 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
7115 // Reevaluate clipping
7124 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
7126 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
7128 // Reevaluate clipping
7135 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7136 * `.toggle( true )` after its #$element is attached to the DOM.
7138 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7139 * it in the right place and with the right dimensions only work correctly while it is attached.
7140 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7141 * strictly enforced, so currently it only generates a warning in the browser console.
7146 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
7149 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
7150 change
= visible
!== this.isVisible();
7152 if ( visible
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
7153 OO
.ui
.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7154 this.warnedUnattached
= true;
7157 if ( change
&& visible
&& ( this.width
|| this.$floatableContainer
) ) {
7158 this.setIdealSize( this.width
|| this.$floatableContainer
.width() );
7162 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7166 this.bindKeyDownListener();
7167 this.bindKeyPressListener();
7169 this.togglePositioning( !!this.$floatableContainer
);
7170 this.toggleClipping( true );
7172 if ( this.getSelectedItem() ) {
7173 this.$focusOwner
.attr( 'aria-activedescendant', this.getSelectedItem().getElementId() );
7174 this.getSelectedItem().scrollElementIntoView( { duration
: 0 } );
7178 if ( this.autoHide
) {
7179 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7182 this.emit( 'ready' );
7184 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7185 this.unbindKeyDownListener();
7186 this.unbindKeyPressListener();
7187 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7188 this.togglePositioning( false );
7189 this.toggleClipping( false );
7197 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7198 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7199 * users can interact with it.
7201 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7202 * OO.ui.DropdownInputWidget instead.
7205 * // Example: A DropdownWidget with a menu that contains three options
7206 * var dropDown = new OO.ui.DropdownWidget( {
7207 * label: 'Dropdown menu: Select a menu option',
7210 * new OO.ui.MenuOptionWidget( {
7214 * new OO.ui.MenuOptionWidget( {
7218 * new OO.ui.MenuOptionWidget( {
7226 * $( 'body' ).append( dropDown.$element );
7228 * dropDown.getMenu().selectItemByData( 'b' );
7230 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
7232 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
7234 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
7237 * @extends OO.ui.Widget
7238 * @mixins OO.ui.mixin.IconElement
7239 * @mixins OO.ui.mixin.IndicatorElement
7240 * @mixins OO.ui.mixin.LabelElement
7241 * @mixins OO.ui.mixin.TitledElement
7242 * @mixins OO.ui.mixin.TabIndexedElement
7245 * @param {Object} [config] Configuration options
7246 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.MenuSelectWidget menu select widget}
7247 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
7248 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
7249 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
7250 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
7252 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
7253 // Configuration initialization
7254 config
= $.extend( { indicator
: 'down' }, config
);
7256 // Parent constructor
7257 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
7259 // Properties (must be set before TabIndexedElement constructor call)
7260 this.$handle
= this.$( '<span>' );
7261 this.$overlay
= config
.$overlay
|| this.$element
;
7263 // Mixin constructors
7264 OO
.ui
.mixin
.IconElement
.call( this, config
);
7265 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7266 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7267 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
7268 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
7271 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend( {
7273 $floatableContainer
: this.$element
7278 click
: this.onClick
.bind( this ),
7279 keydown
: this.onKeyDown
.bind( this ),
7280 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
7281 keypress
: this.menu
.onKeyPressHandler
,
7282 blur
: this.menu
.clearKeyPressBuffer
.bind( this.menu
)
7284 this.menu
.connect( this, {
7285 select
: 'onMenuSelect',
7286 toggle
: 'onMenuToggle'
7291 .addClass( 'oo-ui-dropdownWidget-handle' )
7294 'aria-owns': this.menu
.getElementId(),
7295 'aria-autocomplete': 'list'
7297 .append( this.$icon
, this.$label
, this.$indicator
);
7299 .addClass( 'oo-ui-dropdownWidget' )
7300 .append( this.$handle
);
7301 this.$overlay
.append( this.menu
.$element
);
7306 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
7307 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
7308 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
7309 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
7310 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
7311 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7318 * @return {OO.ui.MenuSelectWidget} Menu of widget
7320 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
7325 * Handles menu select events.
7328 * @param {OO.ui.MenuOptionWidget} item Selected menu item
7330 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
7334 this.setLabel( null );
7338 selectedLabel
= item
.getLabel();
7340 // If the label is a DOM element, clone it, because setLabel will append() it
7341 if ( selectedLabel
instanceof jQuery
) {
7342 selectedLabel
= selectedLabel
.clone();
7345 this.setLabel( selectedLabel
);
7349 * Handle menu toggle events.
7352 * @param {boolean} isVisible Menu toggle event
7354 OO
.ui
.DropdownWidget
.prototype.onMenuToggle = function ( isVisible
) {
7355 this.$element
.toggleClass( 'oo-ui-dropdownWidget-open', isVisible
);
7359 * Handle mouse click events.
7362 * @param {jQuery.Event} e Mouse click event
7364 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
7365 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
7372 * Handle key down events.
7375 * @param {jQuery.Event} e Key down event
7377 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
7379 !this.isDisabled() &&
7381 e
.which
=== OO
.ui
.Keys
.ENTER
||
7383 !this.menu
.isVisible() &&
7385 e
.which
=== OO
.ui
.Keys
.SPACE
||
7386 e
.which
=== OO
.ui
.Keys
.UP
||
7387 e
.which
=== OO
.ui
.Keys
.DOWN
7398 * RadioOptionWidget is an option widget that looks like a radio button.
7399 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
7400 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
7402 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
7405 * @extends OO.ui.OptionWidget
7408 * @param {Object} [config] Configuration options
7410 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
7411 // Configuration initialization
7412 config
= config
|| {};
7414 // Properties (must be done before parent constructor which calls #setDisabled)
7415 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
7417 // Parent constructor
7418 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
7421 // Remove implicit role, we're handling it ourselves
7422 this.radio
.$input
.attr( 'role', 'presentation' );
7424 .addClass( 'oo-ui-radioOptionWidget' )
7425 .attr( 'role', 'radio' )
7426 .attr( 'aria-checked', 'false' )
7427 .removeAttr( 'aria-selected' )
7428 .prepend( this.radio
.$element
);
7433 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
7435 /* Static Properties */
7441 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
7447 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
7453 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
7459 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
7466 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
7467 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
7469 this.radio
.setSelected( state
);
7471 .attr( 'aria-checked', state
.toString() )
7472 .removeAttr( 'aria-selected' );
7480 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
7481 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
7483 this.radio
.setDisabled( this.isDisabled() );
7489 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
7490 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
7491 * an interface for adding, removing and selecting options.
7492 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
7494 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7495 * OO.ui.RadioSelectInputWidget instead.
7498 * // A RadioSelectWidget with RadioOptions.
7499 * var option1 = new OO.ui.RadioOptionWidget( {
7501 * label: 'Selected radio option'
7504 * var option2 = new OO.ui.RadioOptionWidget( {
7506 * label: 'Unselected radio option'
7509 * var radioSelect=new OO.ui.RadioSelectWidget( {
7510 * items: [ option1, option2 ]
7513 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
7514 * radioSelect.selectItem( option1 );
7516 * $( 'body' ).append( radioSelect.$element );
7518 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
7522 * @extends OO.ui.SelectWidget
7523 * @mixins OO.ui.mixin.TabIndexedElement
7526 * @param {Object} [config] Configuration options
7528 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
7529 // Parent constructor
7530 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
7532 // Mixin constructors
7533 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
7537 focus
: this.bindKeyDownListener
.bind( this ),
7538 blur
: this.unbindKeyDownListener
.bind( this )
7543 .addClass( 'oo-ui-radioSelectWidget' )
7544 .attr( 'role', 'radiogroup' );
7549 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
7550 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7553 * MultioptionWidgets are special elements that can be selected and configured with data. The
7554 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
7555 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
7556 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
7558 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Multioptions
7561 * @extends OO.ui.Widget
7562 * @mixins OO.ui.mixin.ItemWidget
7563 * @mixins OO.ui.mixin.LabelElement
7566 * @param {Object} [config] Configuration options
7567 * @cfg {boolean} [selected=false] Whether the option is initially selected
7569 OO
.ui
.MultioptionWidget
= function OoUiMultioptionWidget( config
) {
7570 // Configuration initialization
7571 config
= config
|| {};
7573 // Parent constructor
7574 OO
.ui
.MultioptionWidget
.parent
.call( this, config
);
7576 // Mixin constructors
7577 OO
.ui
.mixin
.ItemWidget
.call( this );
7578 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7581 this.selected
= null;
7585 .addClass( 'oo-ui-multioptionWidget' )
7586 .append( this.$label
);
7587 this.setSelected( config
.selected
);
7592 OO
.inheritClass( OO
.ui
.MultioptionWidget
, OO
.ui
.Widget
);
7593 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.ItemWidget
);
7594 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.LabelElement
);
7601 * A change event is emitted when the selected state of the option changes.
7603 * @param {boolean} selected Whether the option is now selected
7609 * Check if the option is selected.
7611 * @return {boolean} Item is selected
7613 OO
.ui
.MultioptionWidget
.prototype.isSelected = function () {
7614 return this.selected
;
7618 * Set the option’s selected state. In general, all modifications to the selection
7619 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
7620 * method instead of this method.
7622 * @param {boolean} [state=false] Select option
7625 OO
.ui
.MultioptionWidget
.prototype.setSelected = function ( state
) {
7627 if ( this.selected
!== state
) {
7628 this.selected
= state
;
7629 this.emit( 'change', state
);
7630 this.$element
.toggleClass( 'oo-ui-multioptionWidget-selected', state
);
7636 * MultiselectWidget allows selecting multiple options from a list.
7638 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
7640 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
7644 * @extends OO.ui.Widget
7645 * @mixins OO.ui.mixin.GroupWidget
7648 * @param {Object} [config] Configuration options
7649 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
7651 OO
.ui
.MultiselectWidget
= function OoUiMultiselectWidget( config
) {
7652 // Parent constructor
7653 OO
.ui
.MultiselectWidget
.parent
.call( this, config
);
7655 // Configuration initialization
7656 config
= config
|| {};
7658 // Mixin constructors
7659 OO
.ui
.mixin
.GroupWidget
.call( this, config
);
7662 this.aggregate( { change
: 'select' } );
7663 // This is mostly for compatibility with CapsuleMultiselectWidget... normally, 'change' is emitted
7664 // by GroupElement only when items are added/removed
7665 this.connect( this, { select
: [ 'emit', 'change' ] } );
7668 if ( config
.items
) {
7669 this.addItems( config
.items
);
7671 this.$group
.addClass( 'oo-ui-multiselectWidget-group' );
7672 this.$element
.addClass( 'oo-ui-multiselectWidget' )
7673 .append( this.$group
);
7678 OO
.inheritClass( OO
.ui
.MultiselectWidget
, OO
.ui
.Widget
);
7679 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.GroupWidget
);
7686 * A change event is emitted when the set of items changes, or an item is selected or deselected.
7692 * A select event is emitted when an item is selected or deselected.
7698 * Get options that are selected.
7700 * @return {OO.ui.MultioptionWidget[]} Selected options
7702 OO
.ui
.MultiselectWidget
.prototype.getSelectedItems = function () {
7703 return this.items
.filter( function ( item
) {
7704 return item
.isSelected();
7709 * Get the data of options that are selected.
7711 * @return {Object[]|string[]} Values of selected options
7713 OO
.ui
.MultiselectWidget
.prototype.getSelectedItemsData = function () {
7714 return this.getSelectedItems().map( function ( item
) {
7720 * Select options by reference. Options not mentioned in the `items` array will be deselected.
7722 * @param {OO.ui.MultioptionWidget[]} items Items to select
7725 OO
.ui
.MultiselectWidget
.prototype.selectItems = function ( items
) {
7726 this.items
.forEach( function ( item
) {
7727 var selected
= items
.indexOf( item
) !== -1;
7728 item
.setSelected( selected
);
7734 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
7736 * @param {Object[]|string[]} datas Values of items to select
7739 OO
.ui
.MultiselectWidget
.prototype.selectItemsByData = function ( datas
) {
7742 items
= datas
.map( function ( data
) {
7743 return widget
.getItemFromData( data
);
7745 this.selectItems( items
);
7750 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
7751 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
7752 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
7754 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
7757 * @extends OO.ui.MultioptionWidget
7760 * @param {Object} [config] Configuration options
7762 OO
.ui
.CheckboxMultioptionWidget
= function OoUiCheckboxMultioptionWidget( config
) {
7763 // Configuration initialization
7764 config
= config
|| {};
7766 // Properties (must be done before parent constructor which calls #setDisabled)
7767 this.checkbox
= new OO
.ui
.CheckboxInputWidget();
7769 // Parent constructor
7770 OO
.ui
.CheckboxMultioptionWidget
.parent
.call( this, config
);
7773 this.checkbox
.on( 'change', this.onCheckboxChange
.bind( this ) );
7774 this.$element
.on( 'keydown', this.onKeyDown
.bind( this ) );
7778 .addClass( 'oo-ui-checkboxMultioptionWidget' )
7779 .prepend( this.checkbox
.$element
);
7784 OO
.inheritClass( OO
.ui
.CheckboxMultioptionWidget
, OO
.ui
.MultioptionWidget
);
7786 /* Static Properties */
7792 OO
.ui
.CheckboxMultioptionWidget
.static.tagName
= 'label';
7797 * Handle checkbox selected state change.
7801 OO
.ui
.CheckboxMultioptionWidget
.prototype.onCheckboxChange = function () {
7802 this.setSelected( this.checkbox
.isSelected() );
7808 OO
.ui
.CheckboxMultioptionWidget
.prototype.setSelected = function ( state
) {
7809 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setSelected
.call( this, state
);
7810 this.checkbox
.setSelected( state
);
7817 OO
.ui
.CheckboxMultioptionWidget
.prototype.setDisabled = function ( disabled
) {
7818 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
7819 this.checkbox
.setDisabled( this.isDisabled() );
7826 OO
.ui
.CheckboxMultioptionWidget
.prototype.focus = function () {
7827 this.checkbox
.focus();
7831 * Handle key down events.
7834 * @param {jQuery.Event} e
7836 OO
.ui
.CheckboxMultioptionWidget
.prototype.onKeyDown = function ( e
) {
7838 element
= this.getElementGroup(),
7841 if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
|| e
.keyCode
=== OO
.ui
.Keys
.UP
) {
7842 nextItem
= element
.getRelativeFocusableItem( this, -1 );
7843 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
|| e
.keyCode
=== OO
.ui
.Keys
.DOWN
) {
7844 nextItem
= element
.getRelativeFocusableItem( this, 1 );
7854 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
7855 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
7856 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
7857 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
7859 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7860 * OO.ui.CheckboxMultiselectInputWidget instead.
7863 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
7864 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
7867 * label: 'Selected checkbox'
7870 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
7872 * label: 'Unselected checkbox'
7875 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
7876 * items: [ option1, option2 ]
7879 * $( 'body' ).append( multiselect.$element );
7881 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
7884 * @extends OO.ui.MultiselectWidget
7887 * @param {Object} [config] Configuration options
7889 OO
.ui
.CheckboxMultiselectWidget
= function OoUiCheckboxMultiselectWidget( config
) {
7890 // Parent constructor
7891 OO
.ui
.CheckboxMultiselectWidget
.parent
.call( this, config
);
7894 this.$lastClicked
= null;
7897 this.$group
.on( 'click', this.onClick
.bind( this ) );
7901 .addClass( 'oo-ui-checkboxMultiselectWidget' );
7906 OO
.inheritClass( OO
.ui
.CheckboxMultiselectWidget
, OO
.ui
.MultiselectWidget
);
7911 * Get an option by its position relative to the specified item (or to the start of the option array,
7912 * if item is `null`). The direction in which to search through the option array is specified with a
7913 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
7914 * `null` if there are no options in the array.
7916 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
7917 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7918 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
7920 OO
.ui
.CheckboxMultiselectWidget
.prototype.getRelativeFocusableItem = function ( item
, direction
) {
7921 var currentIndex
, nextIndex
, i
,
7922 increase
= direction
> 0 ? 1 : -1,
7923 len
= this.items
.length
;
7926 currentIndex
= this.items
.indexOf( item
);
7927 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
7929 // If no item is selected and moving forward, start at the beginning.
7930 // If moving backward, start at the end.
7931 nextIndex
= direction
> 0 ? 0 : len
- 1;
7934 for ( i
= 0; i
< len
; i
++ ) {
7935 item
= this.items
[ nextIndex
];
7936 if ( item
&& !item
.isDisabled() ) {
7939 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
7945 * Handle click events on checkboxes.
7947 * @param {jQuery.Event} e
7949 OO
.ui
.CheckboxMultiselectWidget
.prototype.onClick = function ( e
) {
7950 var $options
, lastClickedIndex
, nowClickedIndex
, i
, direction
, wasSelected
, items
,
7951 $lastClicked
= this.$lastClicked
,
7952 $nowClicked
= $( e
.target
).closest( '.oo-ui-checkboxMultioptionWidget' )
7953 .not( '.oo-ui-widget-disabled' );
7955 // Allow selecting multiple options at once by Shift-clicking them
7956 if ( $lastClicked
&& $nowClicked
.length
&& e
.shiftKey
) {
7957 $options
= this.$group
.find( '.oo-ui-checkboxMultioptionWidget' );
7958 lastClickedIndex
= $options
.index( $lastClicked
);
7959 nowClickedIndex
= $options
.index( $nowClicked
);
7960 // If it's the same item, either the user is being silly, or it's a fake event generated by the
7961 // browser. In either case we don't need custom handling.
7962 if ( nowClickedIndex
!== lastClickedIndex
) {
7964 wasSelected
= items
[ nowClickedIndex
].isSelected();
7965 direction
= nowClickedIndex
> lastClickedIndex
? 1 : -1;
7967 // This depends on the DOM order of the items and the order of the .items array being the same.
7968 for ( i
= lastClickedIndex
; i
!== nowClickedIndex
; i
+= direction
) {
7969 if ( !items
[ i
].isDisabled() ) {
7970 items
[ i
].setSelected( !wasSelected
);
7973 // For the now-clicked element, use immediate timeout to allow the browser to do its own
7974 // handling first, then set our value. The order in which events happen is different for
7975 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
7976 // non-click actions that change the checkboxes.
7978 setTimeout( function () {
7979 if ( !items
[ nowClickedIndex
].isDisabled() ) {
7980 items
[ nowClickedIndex
].setSelected( !wasSelected
);
7986 if ( $nowClicked
.length
) {
7987 this.$lastClicked
= $nowClicked
;
7992 * FloatingMenuSelectWidget was a menu that would stick under a specified
7993 * container, even when it is inserted elsewhere in the document.
7994 * This functionality is now included in MenuSelectWidget, and FloatingMenuSelectWidget
7995 * is preserved for backwards-compatibility.
7998 * @extends OO.ui.MenuSelectWidget
7999 * @deprecated since v0.21.3, use MenuSelectWidget instead.
8002 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
8003 * Deprecated, omit this parameter and specify `$container` instead.
8004 * @param {Object} [config] Configuration options
8005 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
8007 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
8008 OO
.ui
.warnDeprecation( 'FloatingMenuSelectWidget is deprecated. Use the MenuSelectWidget instead.' );
8010 // Allow 'inputWidget' parameter and config for backwards compatibility
8011 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
8012 config
= inputWidget
;
8013 inputWidget
= config
.inputWidget
;
8016 // Configuration initialization
8017 config
= config
|| {};
8020 this.inputWidget
= inputWidget
; // For backwards compatibility
8021 this.$container
= config
.$floatableContainer
|| config
.$container
|| this.inputWidget
.$element
;
8023 // Parent constructor
8024 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, $.extend( {}, config
, { $floatableContainer
: this.$container
} ) );
8027 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
8028 // For backwards compatibility
8029 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
8034 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
8037 * Progress bars visually display the status of an operation, such as a download,
8038 * and can be either determinate or indeterminate:
8040 * - **determinate** process bars show the percent of an operation that is complete.
8042 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8043 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8044 * not use percentages.
8046 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
8049 * // Examples of determinate and indeterminate progress bars.
8050 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8053 * var progressBar2 = new OO.ui.ProgressBarWidget();
8055 * // Create a FieldsetLayout to layout progress bars
8056 * var fieldset = new OO.ui.FieldsetLayout;
8057 * fieldset.addItems( [
8058 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
8059 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
8061 * $( 'body' ).append( fieldset.$element );
8064 * @extends OO.ui.Widget
8067 * @param {Object} [config] Configuration options
8068 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8069 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
8070 * By default, the progress bar is indeterminate.
8072 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
8073 // Configuration initialization
8074 config
= config
|| {};
8076 // Parent constructor
8077 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
8080 this.$bar
= $( '<div>' );
8081 this.progress
= null;
8084 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
8085 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
8088 role
: 'progressbar',
8090 'aria-valuemax': 100
8092 .addClass( 'oo-ui-progressBarWidget' )
8093 .append( this.$bar
);
8098 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
8100 /* Static Properties */
8106 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
8111 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
8113 * @return {number|boolean} Progress percent
8115 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
8116 return this.progress
;
8120 * Set the percent of the process completed or `false` for an indeterminate process.
8122 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8124 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
8125 this.progress
= progress
;
8127 if ( progress
!== false ) {
8128 this.$bar
.css( 'width', this.progress
+ '%' );
8129 this.$element
.attr( 'aria-valuenow', this.progress
);
8131 this.$bar
.css( 'width', '' );
8132 this.$element
.removeAttr( 'aria-valuenow' );
8134 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress
=== false );
8138 * InputWidget is the base class for all input widgets, which
8139 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
8140 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
8141 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8143 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8147 * @extends OO.ui.Widget
8148 * @mixins OO.ui.mixin.FlaggedElement
8149 * @mixins OO.ui.mixin.TabIndexedElement
8150 * @mixins OO.ui.mixin.TitledElement
8151 * @mixins OO.ui.mixin.AccessKeyedElement
8154 * @param {Object} [config] Configuration options
8155 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8156 * @cfg {string} [value=''] The value of the input.
8157 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8158 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
8159 * before it is accepted.
8161 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
8162 // Configuration initialization
8163 config
= config
|| {};
8165 // Parent constructor
8166 OO
.ui
.InputWidget
.parent
.call( this, config
);
8169 // See #reusePreInfuseDOM about config.$input
8170 this.$input
= config
.$input
|| this.getInputElement( config
);
8172 this.inputFilter
= config
.inputFilter
;
8174 // Mixin constructors
8175 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
8176 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
8177 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8178 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
8181 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
8185 .addClass( 'oo-ui-inputWidget-input' )
8186 .attr( 'name', config
.name
)
8187 .prop( 'disabled', this.isDisabled() );
8189 .addClass( 'oo-ui-inputWidget' )
8190 .append( this.$input
);
8191 this.setValue( config
.value
);
8193 this.setDir( config
.dir
);
8199 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
8200 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
8201 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8202 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
8203 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
8205 /* Static Methods */
8210 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8211 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8212 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
8213 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
8220 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8221 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8222 if ( config
.$input
&& config
.$input
.length
) {
8223 state
.value
= config
.$input
.val();
8224 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
8225 state
.focus
= config
.$input
.is( ':focus' );
8235 * A change event is emitted when the value of the input changes.
8237 * @param {string} value
8243 * Get input element.
8245 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
8246 * different circumstances. The element must have a `value` property (like form elements).
8249 * @param {Object} config Configuration options
8250 * @return {jQuery} Input element
8252 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
8253 return $( '<input>' );
8257 * Handle potentially value-changing events.
8260 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8262 OO
.ui
.InputWidget
.prototype.onEdit = function () {
8264 if ( !this.isDisabled() ) {
8265 // Allow the stack to clear so the value will be updated
8266 setTimeout( function () {
8267 widget
.setValue( widget
.$input
.val() );
8273 * Get the value of the input.
8275 * @return {string} Input value
8277 OO
.ui
.InputWidget
.prototype.getValue = function () {
8278 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8279 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8280 var value
= this.$input
.val();
8281 if ( this.value
!== value
) {
8282 this.setValue( value
);
8288 * Set the directionality of the input.
8290 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
8293 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
8294 this.$input
.prop( 'dir', dir
);
8299 * Set the value of the input.
8301 * @param {string} value New value
8305 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
8306 value
= this.cleanUpValue( value
);
8307 // Update the DOM if it has changed. Note that with cleanUpValue, it
8308 // is possible for the DOM value to change without this.value changing.
8309 if ( this.$input
.val() !== value
) {
8310 this.$input
.val( value
);
8312 if ( this.value
!== value
) {
8314 this.emit( 'change', this.value
);
8320 * Clean up incoming value.
8322 * Ensures value is a string, and converts undefined and null to empty string.
8325 * @param {string} value Original value
8326 * @return {string} Cleaned up value
8328 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
8329 if ( value
=== undefined || value
=== null ) {
8331 } else if ( this.inputFilter
) {
8332 return this.inputFilter( String( value
) );
8334 return String( value
);
8339 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
8340 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
8343 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
8344 OO
.ui
.warnDeprecation( 'InputWidget: simulateLabelClick() is deprecated.' );
8345 if ( !this.isDisabled() ) {
8346 if ( this.$input
.is( ':checkbox, :radio' ) ) {
8347 this.$input
.click();
8349 if ( this.$input
.is( ':input' ) ) {
8350 this.$input
[ 0 ].focus();
8358 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
8359 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8360 if ( this.$input
) {
8361 this.$input
.prop( 'disabled', this.isDisabled() );
8369 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
8370 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8371 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
8372 this.setValue( state
.value
);
8374 if ( state
.focus
) {
8380 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
8381 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
8382 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
8383 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
8384 * [OOjs UI documentation on MediaWiki] [1] for more information.
8387 * // A ButtonInputWidget rendered as an HTML button, the default.
8388 * var button = new OO.ui.ButtonInputWidget( {
8389 * label: 'Input button',
8393 * $( 'body' ).append( button.$element );
8395 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
8398 * @extends OO.ui.InputWidget
8399 * @mixins OO.ui.mixin.ButtonElement
8400 * @mixins OO.ui.mixin.IconElement
8401 * @mixins OO.ui.mixin.IndicatorElement
8402 * @mixins OO.ui.mixin.LabelElement
8403 * @mixins OO.ui.mixin.TitledElement
8406 * @param {Object} [config] Configuration options
8407 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
8408 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
8409 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
8410 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
8411 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
8413 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
8414 // Configuration initialization
8415 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
8417 // See InputWidget#reusePreInfuseDOM about config.$input
8418 if ( config
.$input
) {
8419 config
.$input
.empty();
8422 // Properties (must be set before parent constructor, which calls #setValue)
8423 this.useInputTag
= config
.useInputTag
;
8425 // Parent constructor
8426 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
8428 // Mixin constructors
8429 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
8430 OO
.ui
.mixin
.IconElement
.call( this, config
);
8431 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
8432 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8433 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8436 if ( !config
.useInputTag
) {
8437 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
8439 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
8444 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
8445 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
8446 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
8447 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
8448 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
8449 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
8451 /* Static Properties */
8457 OO
.ui
.ButtonInputWidget
.static.tagName
= 'span';
8465 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
8467 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
8468 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
8474 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
8476 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
8477 * text, or `null` for no label
8480 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
8481 if ( typeof label
=== 'function' ) {
8482 label
= OO
.ui
.resolveMsg( label
);
8485 if ( this.useInputTag
) {
8486 // Discard non-plaintext labels
8487 if ( typeof label
!== 'string' ) {
8491 this.$input
.val( label
);
8494 return OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
8498 * Set the value of the input.
8500 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
8501 * they do not support {@link #value values}.
8503 * @param {string} value New value
8506 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
8507 if ( !this.useInputTag
) {
8508 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
8516 OO
.ui
.ButtonInputWidget
.prototype.getInputId = function () {
8517 // Disable generating `<label>` elements for buttons. One would very rarely need additional label
8518 // for a button, and it's already a big clickable target, and it causes unexpected rendering.
8523 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
8524 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
8525 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
8526 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
8528 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8531 * // An example of selected, unselected, and disabled checkbox inputs
8532 * var checkbox1=new OO.ui.CheckboxInputWidget( {
8536 * var checkbox2=new OO.ui.CheckboxInputWidget( {
8539 * var checkbox3=new OO.ui.CheckboxInputWidget( {
8543 * // Create a fieldset layout with fields for each checkbox.
8544 * var fieldset = new OO.ui.FieldsetLayout( {
8545 * label: 'Checkboxes'
8547 * fieldset.addItems( [
8548 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
8549 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
8550 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
8552 * $( 'body' ).append( fieldset.$element );
8554 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8557 * @extends OO.ui.InputWidget
8560 * @param {Object} [config] Configuration options
8561 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
8563 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
8564 // Configuration initialization
8565 config
= config
|| {};
8567 // Parent constructor
8568 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
8572 .addClass( 'oo-ui-checkboxInputWidget' )
8573 // Required for pretty styling in MediaWiki theme
8574 .append( $( '<span>' ) );
8575 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
8580 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
8582 /* Static Properties */
8588 OO
.ui
.CheckboxInputWidget
.static.tagName
= 'span';
8590 /* Static Methods */
8595 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8596 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8597 state
.checked
= config
.$input
.prop( 'checked' );
8607 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
8608 return $( '<input>' ).attr( 'type', 'checkbox' );
8614 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
8616 if ( !this.isDisabled() ) {
8617 // Allow the stack to clear so the value will be updated
8618 setTimeout( function () {
8619 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
8625 * Set selection state of this checkbox.
8627 * @param {boolean} state `true` for selected
8630 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
8632 if ( this.selected
!== state
) {
8633 this.selected
= state
;
8634 this.$input
.prop( 'checked', this.selected
);
8635 this.emit( 'change', this.selected
);
8641 * Check if this checkbox is selected.
8643 * @return {boolean} Checkbox is selected
8645 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
8646 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8647 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8648 var selected
= this.$input
.prop( 'checked' );
8649 if ( this.selected
!== selected
) {
8650 this.setSelected( selected
);
8652 return this.selected
;
8658 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
8659 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8660 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
8661 this.setSelected( state
.checked
);
8666 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
8667 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
8668 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
8669 * more information about input widgets.
8671 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
8672 * are no options. If no `value` configuration option is provided, the first option is selected.
8673 * If you need a state representing no value (no option being selected), use a DropdownWidget.
8675 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
8678 * // Example: A DropdownInputWidget with three options
8679 * var dropdownInput = new OO.ui.DropdownInputWidget( {
8681 * { data: 'a', label: 'First' },
8682 * { data: 'b', label: 'Second'},
8683 * { data: 'c', label: 'Third' }
8686 * $( 'body' ).append( dropdownInput.$element );
8688 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8691 * @extends OO.ui.InputWidget
8692 * @mixins OO.ui.mixin.TitledElement
8695 * @param {Object} [config] Configuration options
8696 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8697 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
8699 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
8700 // Configuration initialization
8701 config
= config
|| {};
8703 // See InputWidget#reusePreInfuseDOM about config.$input
8704 if ( config
.$input
) {
8705 config
.$input
.addClass( 'oo-ui-element-hidden' );
8708 // Properties (must be done before parent constructor which calls #setDisabled)
8709 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
8711 // Parent constructor
8712 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
8714 // Mixin constructors
8715 OO
.ui
.mixin
.TitledElement
.call( this, config
);
8718 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
8721 this.setOptions( config
.options
|| [] );
8723 .addClass( 'oo-ui-dropdownInputWidget' )
8724 .append( this.dropdownWidget
.$element
);
8725 this.setTabIndexedElement( null );
8730 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
8731 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
8739 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
8740 return $( '<input>' ).attr( 'type', 'hidden' );
8744 * Handles menu select events.
8747 * @param {OO.ui.MenuOptionWidget} item Selected menu item
8749 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
8750 this.setValue( item
.getData() );
8756 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
8758 value
= this.cleanUpValue( value
);
8759 this.dropdownWidget
.getMenu().selectItemByData( value
);
8760 // Only allow setting values that are actually present in the dropdown
8761 selected
= this.dropdownWidget
.getMenu().getSelectedItem();
8762 value
= selected
? selected
.getData() : '';
8763 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
8770 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
8771 this.dropdownWidget
.setDisabled( state
);
8772 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8777 * Set the options available for this input.
8779 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8782 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
8784 value
= this.getValue(),
8787 // Rebuild the dropdown menu
8788 this.dropdownWidget
.getMenu()
8790 .addItems( options
.map( function ( opt
) {
8791 var optValue
= widget
.cleanUpValue( opt
.data
);
8793 if ( opt
.optgroup
=== undefined ) {
8794 return new OO
.ui
.MenuOptionWidget( {
8796 label
: opt
.label
!== undefined ? opt
.label
: optValue
8799 return new OO
.ui
.MenuSectionOptionWidget( {
8805 // Restore the previous value, or reset to something sensible
8806 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
8807 // Previous value is still available, ensure consistency with the dropdown
8808 this.setValue( value
);
8810 // No longer valid, reset
8811 if ( options
.length
) {
8812 this.setValue( options
[ 0 ].data
);
8822 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
8823 this.dropdownWidget
.focus();
8830 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
8831 this.dropdownWidget
.blur();
8836 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
8837 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
8838 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
8839 * please see the [OOjs UI documentation on MediaWiki][1].
8841 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8844 * // An example of selected, unselected, and disabled radio inputs
8845 * var radio1 = new OO.ui.RadioInputWidget( {
8849 * var radio2 = new OO.ui.RadioInputWidget( {
8852 * var radio3 = new OO.ui.RadioInputWidget( {
8856 * // Create a fieldset layout with fields for each radio button.
8857 * var fieldset = new OO.ui.FieldsetLayout( {
8858 * label: 'Radio inputs'
8860 * fieldset.addItems( [
8861 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
8862 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
8863 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
8865 * $( 'body' ).append( fieldset.$element );
8867 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8870 * @extends OO.ui.InputWidget
8873 * @param {Object} [config] Configuration options
8874 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
8876 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
8877 // Configuration initialization
8878 config
= config
|| {};
8880 // Parent constructor
8881 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
8885 .addClass( 'oo-ui-radioInputWidget' )
8886 // Required for pretty styling in MediaWiki theme
8887 .append( $( '<span>' ) );
8888 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
8893 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
8895 /* Static Properties */
8901 OO
.ui
.RadioInputWidget
.static.tagName
= 'span';
8903 /* Static Methods */
8908 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8909 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8910 state
.checked
= config
.$input
.prop( 'checked' );
8920 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
8921 return $( '<input>' ).attr( 'type', 'radio' );
8927 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
8928 // RadioInputWidget doesn't track its state.
8932 * Set selection state of this radio button.
8934 * @param {boolean} state `true` for selected
8937 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
8938 // RadioInputWidget doesn't track its state.
8939 this.$input
.prop( 'checked', state
);
8944 * Check if this radio button is selected.
8946 * @return {boolean} Radio is selected
8948 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
8949 return this.$input
.prop( 'checked' );
8955 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
8956 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8957 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
8958 this.setSelected( state
.checked
);
8963 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
8964 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
8965 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
8966 * more information about input widgets.
8968 * This and OO.ui.DropdownInputWidget support the same configuration options.
8971 * // Example: A RadioSelectInputWidget with three options
8972 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
8974 * { data: 'a', label: 'First' },
8975 * { data: 'b', label: 'Second'},
8976 * { data: 'c', label: 'Third' }
8979 * $( 'body' ).append( radioSelectInput.$element );
8981 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8984 * @extends OO.ui.InputWidget
8987 * @param {Object} [config] Configuration options
8988 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8990 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
8991 // Configuration initialization
8992 config
= config
|| {};
8994 // Properties (must be done before parent constructor which calls #setDisabled)
8995 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
8997 // Parent constructor
8998 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
9001 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
9004 this.setOptions( config
.options
|| [] );
9006 .addClass( 'oo-ui-radioSelectInputWidget' )
9007 .append( this.radioSelectWidget
.$element
);
9008 this.setTabIndexedElement( null );
9013 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
9015 /* Static Methods */
9020 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9021 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9022 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
9029 OO
.ui
.RadioSelectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9030 config
= OO
.ui
.RadioSelectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9031 // Cannot reuse the `<input type=radio>` set
9032 delete config
.$input
;
9042 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
9043 return $( '<input>' ).attr( 'type', 'hidden' );
9047 * Handles menu select events.
9050 * @param {OO.ui.RadioOptionWidget} item Selected menu item
9052 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
9053 this.setValue( item
.getData() );
9059 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
9060 value
= this.cleanUpValue( value
);
9061 this.radioSelectWidget
.selectItemByData( value
);
9062 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
9069 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
9070 this.radioSelectWidget
.setDisabled( state
);
9071 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9076 * Set the options available for this input.
9078 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9081 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
9083 value
= this.getValue(),
9086 // Rebuild the radioSelect menu
9087 this.radioSelectWidget
9089 .addItems( options
.map( function ( opt
) {
9090 var optValue
= widget
.cleanUpValue( opt
.data
);
9091 return new OO
.ui
.RadioOptionWidget( {
9093 label
: opt
.label
!== undefined ? opt
.label
: optValue
9097 // Restore the previous value, or reset to something sensible
9098 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
9099 // Previous value is still available, ensure consistency with the radioSelect
9100 this.setValue( value
);
9102 // No longer valid, reset
9103 if ( options
.length
) {
9104 this.setValue( options
[ 0 ].data
);
9114 OO
.ui
.RadioSelectInputWidget
.prototype.focus = function () {
9115 this.radioSelectWidget
.focus();
9122 OO
.ui
.RadioSelectInputWidget
.prototype.blur = function () {
9123 this.radioSelectWidget
.blur();
9128 * CheckboxMultiselectInputWidget is a
9129 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
9130 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
9131 * HTML `<input type=checkbox>` tags. Please see the [OOjs UI documentation on MediaWiki][1] for
9132 * more information about input widgets.
9135 * // Example: A CheckboxMultiselectInputWidget with three options
9136 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
9138 * { data: 'a', label: 'First' },
9139 * { data: 'b', label: 'Second'},
9140 * { data: 'c', label: 'Third' }
9143 * $( 'body' ).append( multiselectInput.$element );
9145 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9148 * @extends OO.ui.InputWidget
9151 * @param {Object} [config] Configuration options
9152 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
9154 OO
.ui
.CheckboxMultiselectInputWidget
= function OoUiCheckboxMultiselectInputWidget( config
) {
9155 // Configuration initialization
9156 config
= config
|| {};
9158 // Properties (must be done before parent constructor which calls #setDisabled)
9159 this.checkboxMultiselectWidget
= new OO
.ui
.CheckboxMultiselectWidget();
9161 // Parent constructor
9162 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.call( this, config
);
9165 this.inputName
= config
.name
;
9169 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
9170 .append( this.checkboxMultiselectWidget
.$element
);
9171 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
9172 this.$input
.detach();
9173 this.setOptions( config
.options
|| [] );
9174 // Have to repeat this from parent, as we need options to be set up for this to make sense
9175 this.setValue( config
.value
);
9180 OO
.inheritClass( OO
.ui
.CheckboxMultiselectInputWidget
, OO
.ui
.InputWidget
);
9182 /* Static Methods */
9187 OO
.ui
.CheckboxMultiselectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9188 var state
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9189 state
.value
= $( node
).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9190 .toArray().map( function ( el
) { return el
.value
; } );
9197 OO
.ui
.CheckboxMultiselectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9198 config
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9199 // Cannot reuse the `<input type=checkbox>` set
9200 delete config
.$input
;
9210 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getInputElement = function () {
9212 return $( '<unused>' );
9218 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getValue = function () {
9219 var value
= this.$element
.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9220 .toArray().map( function ( el
) { return el
.value
; } );
9221 if ( this.value
!== value
) {
9222 this.setValue( value
);
9230 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setValue = function ( value
) {
9231 value
= this.cleanUpValue( value
);
9232 this.checkboxMultiselectWidget
.selectItemsByData( value
);
9233 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setValue
.call( this, value
);
9238 * Clean up incoming value.
9240 * @param {string[]} value Original value
9241 * @return {string[]} Cleaned up value
9243 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.cleanUpValue = function ( value
) {
9246 if ( !Array
.isArray( value
) ) {
9249 for ( i
= 0; i
< value
.length
; i
++ ) {
9251 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( this, value
[ i
] );
9252 // Remove options that we don't have here
9253 if ( !this.checkboxMultiselectWidget
.getItemFromData( singleValue
) ) {
9256 cleanValue
.push( singleValue
);
9264 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setDisabled = function ( state
) {
9265 this.checkboxMultiselectWidget
.setDisabled( state
);
9266 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9271 * Set the options available for this input.
9273 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
9276 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptions = function ( options
) {
9279 // Rebuild the checkboxMultiselectWidget menu
9280 this.checkboxMultiselectWidget
9282 .addItems( options
.map( function ( opt
) {
9283 var optValue
, item
, optDisabled
;
9285 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( widget
, opt
.data
);
9286 optDisabled
= opt
.disabled
!== undefined ? opt
.disabled
: false;
9287 item
= new OO
.ui
.CheckboxMultioptionWidget( {
9289 label
: opt
.label
!== undefined ? opt
.label
: optValue
,
9290 disabled
: optDisabled
9292 // Set the 'name' and 'value' for form submission
9293 item
.checkbox
.$input
.attr( 'name', widget
.inputName
);
9294 item
.checkbox
.setValue( optValue
);
9298 // Re-set the value, checking the checkboxes as needed.
9299 // This will also get rid of any stale options that we just removed.
9300 this.setValue( this.getValue() );
9306 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
9307 * size of the field as well as its presentation. In addition, these widgets can be configured
9308 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
9309 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
9310 * which modifies incoming values rather than validating them.
9311 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9313 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9316 * // Example of a text input widget
9317 * var textInput = new OO.ui.TextInputWidget( {
9318 * value: 'Text input'
9320 * $( 'body' ).append( textInput.$element );
9322 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9325 * @extends OO.ui.InputWidget
9326 * @mixins OO.ui.mixin.IconElement
9327 * @mixins OO.ui.mixin.IndicatorElement
9328 * @mixins OO.ui.mixin.PendingElement
9329 * @mixins OO.ui.mixin.LabelElement
9332 * @param {Object} [config] Configuration options
9333 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
9334 * 'email', 'url' or 'number'. Ignored if `multiline` is true.
9336 * Some values of `type` result in additional behaviors:
9338 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
9339 * empties the text field
9340 * @cfg {string} [placeholder] Placeholder text
9341 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
9342 * instruct the browser to focus this widget.
9343 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
9344 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
9345 * @cfg {boolean} [multiline=false] Allow multiple lines of text
9346 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
9347 * specifies minimum number of rows to display.
9348 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
9349 * Use the #maxRows config to specify a maximum number of displayed rows.
9350 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
9351 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
9352 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
9353 * the value or placeholder text: `'before'` or `'after'`
9354 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
9355 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
9356 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
9357 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
9358 * (the value must contain only numbers); when RegExp, a regular expression that must match the
9359 * value for it to be considered valid; when Function, a function receiving the value as parameter
9360 * that must return true, or promise resolving to true, for it to be considered valid.
9362 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
9363 // Configuration initialization
9364 config
= $.extend( {
9366 labelPosition
: 'after'
9369 if ( config
.type
=== 'search' ) {
9370 OO
.ui
.warnDeprecation( 'TextInputWidget: config.type=\'search\' is deprecated. Use the SearchInputWidget instead. See T148471 for details.' );
9371 if ( config
.icon
=== undefined ) {
9372 config
.icon
= 'search';
9374 // indicator: 'clear' is set dynamically later, depending on value
9377 // Parent constructor
9378 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
9380 // Mixin constructors
9381 OO
.ui
.mixin
.IconElement
.call( this, config
);
9382 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
9383 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
9384 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9387 this.type
= this.getSaneType( config
);
9388 this.readOnly
= false;
9389 this.required
= false;
9390 this.multiline
= !!config
.multiline
;
9391 this.autosize
= !!config
.autosize
;
9392 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
9393 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
9394 this.validate
= null;
9395 this.styleHeight
= null;
9396 this.scrollWidth
= null;
9398 // Clone for resizing
9399 if ( this.autosize
) {
9400 this.$clone
= this.$input
9402 .insertAfter( this.$input
)
9403 .attr( 'aria-hidden', 'true' )
9404 .addClass( 'oo-ui-element-hidden' );
9407 this.setValidation( config
.validate
);
9408 this.setLabelPosition( config
.labelPosition
);
9412 keypress
: this.onKeyPress
.bind( this ),
9413 blur
: this.onBlur
.bind( this ),
9414 focus
: this.onFocus
.bind( this )
9416 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
9417 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
9418 this.on( 'labelChange', this.updatePosition
.bind( this ) );
9419 this.connect( this, {
9421 disable
: 'onDisable'
9423 this.on( 'change', OO
.ui
.debounce( this.onDebouncedChange
.bind( this ), 250 ) );
9427 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
9428 .append( this.$icon
, this.$indicator
);
9429 this.setReadOnly( !!config
.readOnly
);
9430 this.setRequired( !!config
.required
);
9431 this.updateSearchIndicator();
9432 if ( config
.placeholder
!== undefined ) {
9433 this.$input
.attr( 'placeholder', config
.placeholder
);
9435 if ( config
.maxLength
!== undefined ) {
9436 this.$input
.attr( 'maxlength', config
.maxLength
);
9438 if ( config
.autofocus
) {
9439 this.$input
.attr( 'autofocus', 'autofocus' );
9441 if ( config
.autocomplete
=== false ) {
9442 this.$input
.attr( 'autocomplete', 'off' );
9443 // Turning off autocompletion also disables "form caching" when the user navigates to a
9444 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
9446 beforeunload: function () {
9447 this.$input
.removeAttr( 'autocomplete' );
9449 pageshow: function () {
9450 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
9451 // whole page... it shouldn't hurt, though.
9452 this.$input
.attr( 'autocomplete', 'off' );
9456 if ( this.multiline
&& config
.rows
) {
9457 this.$input
.attr( 'rows', config
.rows
);
9459 if ( this.label
|| config
.autosize
) {
9460 this.isWaitingToBeAttached
= true;
9461 this.installParentChangeDetector();
9467 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
9468 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
9469 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
9470 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
9471 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
9473 /* Static Properties */
9475 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
9480 /* Static Methods */
9485 OO
.ui
.TextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9486 var state
= OO
.ui
.TextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9487 if ( config
.multiline
) {
9488 state
.scrollTop
= config
.$input
.scrollTop();
9496 * An `enter` event is emitted when the user presses 'enter' inside the text box.
9498 * Not emitted if the input is multiline.
9504 * A `resize` event is emitted when autosize is set and the widget resizes
9512 * Handle icon mouse down events.
9515 * @param {jQuery.Event} e Mouse down event
9517 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
9518 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
9525 * Handle indicator mouse down events.
9528 * @param {jQuery.Event} e Mouse down event
9530 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
9531 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
9532 if ( this.type
=== 'search' ) {
9533 // Clear the text field
9534 this.setValue( '' );
9542 * Handle key press events.
9545 * @param {jQuery.Event} e Key press event
9546 * @fires enter If enter key is pressed and input is not multiline
9548 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
9549 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
9550 this.emit( 'enter', e
);
9555 * Handle blur events.
9558 * @param {jQuery.Event} e Blur event
9560 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
9561 this.setValidityFlag();
9565 * Handle focus events.
9568 * @param {jQuery.Event} e Focus event
9570 OO
.ui
.TextInputWidget
.prototype.onFocus = function () {
9571 if ( this.isWaitingToBeAttached
) {
9572 // If we've received focus, then we must be attached to the document, and if
9573 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
9574 this.onElementAttach();
9576 this.setValidityFlag( true );
9580 * Handle element attach events.
9583 * @param {jQuery.Event} e Element attach event
9585 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
9586 this.isWaitingToBeAttached
= false;
9587 // Any previously calculated size is now probably invalid if we reattached elsewhere
9588 this.valCache
= null;
9590 this.positionLabel();
9594 * Handle change events.
9596 * @param {string} value
9599 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
9600 this.updateSearchIndicator();
9605 * Handle debounced change events.
9607 * @param {string} value
9610 OO
.ui
.TextInputWidget
.prototype.onDebouncedChange = function () {
9611 this.setValidityFlag();
9615 * Handle disable events.
9617 * @param {boolean} disabled Element is disabled
9620 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
9621 this.updateSearchIndicator();
9625 * Check if the input is {@link #readOnly read-only}.
9629 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
9630 return this.readOnly
;
9634 * Set the {@link #readOnly read-only} state of the input.
9636 * @param {boolean} state Make input read-only
9639 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
9640 this.readOnly
= !!state
;
9641 this.$input
.prop( 'readOnly', this.readOnly
);
9642 this.updateSearchIndicator();
9647 * Check if the input is {@link #required required}.
9651 OO
.ui
.TextInputWidget
.prototype.isRequired = function () {
9652 return this.required
;
9656 * Set the {@link #required required} state of the input.
9658 * @param {boolean} state Make input required
9661 OO
.ui
.TextInputWidget
.prototype.setRequired = function ( state
) {
9662 this.required
= !!state
;
9663 if ( this.required
) {
9665 .prop( 'required', true )
9666 .attr( 'aria-required', 'true' );
9667 if ( this.getIndicator() === null ) {
9668 this.setIndicator( 'required' );
9672 .prop( 'required', false )
9673 .removeAttr( 'aria-required' );
9674 if ( this.getIndicator() === 'required' ) {
9675 this.setIndicator( null );
9678 this.updateSearchIndicator();
9683 * Support function for making #onElementAttach work across browsers.
9685 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
9686 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
9688 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
9689 * first time that the element gets attached to the documented.
9691 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
9692 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
9693 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
9696 if ( MutationObserver
) {
9697 // The new way. If only it wasn't so ugly.
9699 if ( this.isElementAttached() ) {
9700 // Widget is attached already, do nothing. This breaks the functionality of this function when
9701 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
9702 // would require observation of the whole document, which would hurt performance of other,
9703 // more important code.
9707 // Find topmost node in the tree
9708 topmostNode
= this.$element
[ 0 ];
9709 while ( topmostNode
.parentNode
) {
9710 topmostNode
= topmostNode
.parentNode
;
9713 // We have no way to detect the $element being attached somewhere without observing the entire
9714 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
9715 // parent node of $element, and instead detect when $element is removed from it (and thus
9716 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
9717 // doesn't get attached, we end up back here and create the parent.
9719 mutationObserver
= new MutationObserver( function ( mutations
) {
9720 var i
, j
, removedNodes
;
9721 for ( i
= 0; i
< mutations
.length
; i
++ ) {
9722 removedNodes
= mutations
[ i
].removedNodes
;
9723 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
9724 if ( removedNodes
[ j
] === topmostNode
) {
9725 setTimeout( onRemove
, 0 );
9732 onRemove = function () {
9733 // If the node was attached somewhere else, report it
9734 if ( widget
.isElementAttached() ) {
9735 widget
.onElementAttach();
9737 mutationObserver
.disconnect();
9738 widget
.installParentChangeDetector();
9741 // Create a fake parent and observe it
9742 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
9743 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
9745 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
9746 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
9747 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
9752 * Automatically adjust the size of the text input.
9754 * This only affects #multiline inputs that are {@link #autosize autosized}.
9759 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
9760 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
9761 idealHeight
, newHeight
, scrollWidth
, property
;
9763 if ( this.isWaitingToBeAttached
) {
9764 // #onElementAttach will be called soon, which calls this method
9768 if ( this.multiline
&& this.$input
.val() !== this.valCache
) {
9769 if ( this.autosize
) {
9771 .val( this.$input
.val() )
9772 .attr( 'rows', this.minRows
)
9773 // Set inline height property to 0 to measure scroll height
9774 .css( 'height', 0 );
9776 this.$clone
.removeClass( 'oo-ui-element-hidden' );
9778 this.valCache
= this.$input
.val();
9780 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
9782 // Remove inline height property to measure natural heights
9783 this.$clone
.css( 'height', '' );
9784 innerHeight
= this.$clone
.innerHeight();
9785 outerHeight
= this.$clone
.outerHeight();
9787 // Measure max rows height
9789 .attr( 'rows', this.maxRows
)
9790 .css( 'height', 'auto' )
9792 maxInnerHeight
= this.$clone
.innerHeight();
9794 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
9795 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
9796 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
9797 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
9799 this.$clone
.addClass( 'oo-ui-element-hidden' );
9801 // Only apply inline height when expansion beyond natural height is needed
9802 // Use the difference between the inner and outer height as a buffer
9803 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
9804 if ( newHeight
!== this.styleHeight
) {
9805 this.$input
.css( 'height', newHeight
);
9806 this.styleHeight
= newHeight
;
9807 this.emit( 'resize' );
9810 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
9811 if ( scrollWidth
!== this.scrollWidth
) {
9812 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
9814 this.$label
.css( { right
: '', left
: '' } );
9815 this.$indicator
.css( { right
: '', left
: '' } );
9817 if ( scrollWidth
) {
9818 this.$indicator
.css( property
, scrollWidth
);
9819 if ( this.labelPosition
=== 'after' ) {
9820 this.$label
.css( property
, scrollWidth
);
9824 this.scrollWidth
= scrollWidth
;
9825 this.positionLabel();
9835 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
9836 if ( config
.multiline
) {
9837 return $( '<textarea>' );
9838 } else if ( this.getSaneType( config
) === 'number' ) {
9839 return $( '<input>' )
9840 .attr( 'step', 'any' )
9841 .attr( 'type', 'number' );
9843 return $( '<input>' ).attr( 'type', this.getSaneType( config
) );
9848 * Get sanitized value for 'type' for given config.
9850 * @param {Object} config Configuration options
9851 * @return {string|null}
9854 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
9855 var allowedTypes
= [
9863 return allowedTypes
.indexOf( config
.type
) !== -1 ? config
.type
: 'text';
9867 * Check if the input supports multiple lines.
9871 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
9872 return !!this.multiline
;
9876 * Check if the input automatically adjusts its size.
9880 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
9881 return !!this.autosize
;
9885 * Focus the input and select a specified range within the text.
9887 * @param {number} from Select from offset
9888 * @param {number} [to] Select to offset, defaults to from
9891 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
9892 var isBackwards
, start
, end
,
9893 input
= this.$input
[ 0 ];
9897 isBackwards
= to
< from;
9898 start
= isBackwards
? to
: from;
9899 end
= isBackwards
? from : to
;
9904 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
9906 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
9907 // Rather than expensively check if the input is attached every time, just check
9908 // if it was the cause of an error being thrown. If not, rethrow the error.
9909 if ( this.getElementDocument().body
.contains( input
) ) {
9917 * Get an object describing the current selection range in a directional manner
9919 * @return {Object} Object containing 'from' and 'to' offsets
9921 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
9922 var input
= this.$input
[ 0 ],
9923 start
= input
.selectionStart
,
9924 end
= input
.selectionEnd
,
9925 isBackwards
= input
.selectionDirection
=== 'backward';
9928 from: isBackwards
? end
: start
,
9929 to
: isBackwards
? start
: end
9934 * Get the length of the text input value.
9936 * This could differ from the length of #getValue if the
9937 * value gets filtered
9939 * @return {number} Input length
9941 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
9942 return this.$input
[ 0 ].value
.length
;
9946 * Focus the input and select the entire text.
9950 OO
.ui
.TextInputWidget
.prototype.select = function () {
9951 return this.selectRange( 0, this.getInputLength() );
9955 * Focus the input and move the cursor to the start.
9959 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
9960 return this.selectRange( 0 );
9964 * Focus the input and move the cursor to the end.
9968 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
9969 return this.selectRange( this.getInputLength() );
9973 * Insert new content into the input.
9975 * @param {string} content Content to be inserted
9978 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
9980 range
= this.getRange(),
9981 value
= this.getValue();
9983 start
= Math
.min( range
.from, range
.to
);
9984 end
= Math
.max( range
.from, range
.to
);
9986 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
9987 this.selectRange( start
+ content
.length
);
9992 * Insert new content either side of a selection.
9994 * @param {string} pre Content to be inserted before the selection
9995 * @param {string} post Content to be inserted after the selection
9998 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
10000 range
= this.getRange(),
10001 offset
= pre
.length
;
10003 start
= Math
.min( range
.from, range
.to
);
10004 end
= Math
.max( range
.from, range
.to
);
10006 this.selectRange( start
).insertContent( pre
);
10007 this.selectRange( offset
+ end
).insertContent( post
);
10009 this.selectRange( offset
+ start
, offset
+ end
);
10014 * Set the validation pattern.
10016 * The validation pattern is either a regular expression, a function, or the symbolic name of a
10017 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
10018 * value must contain only numbers).
10020 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
10021 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10023 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
10024 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
10025 this.validate
= validate
;
10027 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
10032 * Sets the 'invalid' flag appropriately.
10034 * @param {boolean} [isValid] Optionally override validation result
10036 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
10038 setFlag = function ( valid
) {
10040 widget
.$input
.attr( 'aria-invalid', 'true' );
10042 widget
.$input
.removeAttr( 'aria-invalid' );
10044 widget
.setFlags( { invalid
: !valid
} );
10047 if ( isValid
!== undefined ) {
10048 setFlag( isValid
);
10050 this.getValidity().then( function () {
10059 * Get the validity of current value.
10061 * This method returns a promise that resolves if the value is valid and rejects if
10062 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10064 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10066 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
10069 function rejectOrResolve( valid
) {
10071 return $.Deferred().resolve().promise();
10073 return $.Deferred().reject().promise();
10077 // Check browser validity and reject if it is invalid
10079 this.$input
[ 0 ].checkValidity
!== undefined &&
10080 this.$input
[ 0 ].checkValidity() === false
10082 return rejectOrResolve( false );
10085 // Run our checks if the browser thinks the field is valid
10086 if ( this.validate
instanceof Function
) {
10087 result
= this.validate( this.getValue() );
10088 if ( result
&& $.isFunction( result
.promise
) ) {
10089 return result
.promise().then( function ( valid
) {
10090 return rejectOrResolve( valid
);
10093 return rejectOrResolve( result
);
10096 return rejectOrResolve( this.getValue().match( this.validate
) );
10101 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
10103 * @param {string} labelPosition Label position, 'before' or 'after'
10106 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
10107 this.labelPosition
= labelPosition
;
10108 if ( this.label
) {
10109 // If there is no label and we only change the position, #updatePosition is a no-op,
10110 // but it takes really a lot of work to do nothing.
10111 this.updatePosition();
10117 * Update the position of the inline label.
10119 * This method is called by #setLabelPosition, and can also be called on its own if
10120 * something causes the label to be mispositioned.
10124 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
10125 var after
= this.labelPosition
=== 'after';
10128 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
10129 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
10131 this.valCache
= null;
10132 this.scrollWidth
= null;
10134 this.positionLabel();
10140 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
10141 * already empty or when it's not editable.
10143 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
10144 if ( this.type
=== 'search' ) {
10145 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
10146 this.setIndicator( null );
10148 this.setIndicator( 'clear' );
10154 * Position the label by setting the correct padding on the input.
10159 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
10160 var after
, rtl
, property
;
10162 if ( this.isWaitingToBeAttached
) {
10163 // #onElementAttach will be called soon, which calls this method
10167 // Clear old values
10169 // Clear old values if present
10171 'padding-right': '',
10175 if ( this.label
) {
10176 this.$element
.append( this.$label
);
10178 this.$label
.detach();
10182 after
= this.labelPosition
=== 'after';
10183 rtl
= this.$element
.css( 'direction' ) === 'rtl';
10184 property
= after
=== rtl
? 'padding-left' : 'padding-right';
10186 this.$input
.css( property
, this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 ) );
10194 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
10195 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
10196 if ( state
.scrollTop
!== undefined ) {
10197 this.$input
.scrollTop( state
.scrollTop
);
10203 * @extends OO.ui.TextInputWidget
10206 * @param {Object} [config] Configuration options
10208 OO
.ui
.SearchInputWidget
= function OoUiSearchInputWidget( config
) {
10209 config
= $.extend( {
10213 // Set type to text so that TextInputWidget doesn't
10214 // get stuck in an infinite loop.
10215 config
.type
= 'text';
10217 // Parent constructor
10218 OO
.ui
.SearchInputWidget
.parent
.call( this, config
);
10221 this.$element
.addClass( 'oo-ui-textInputWidget-type-search' );
10222 this.updateSearchIndicator();
10223 this.connect( this, {
10224 disable
: 'onDisable'
10230 OO
.inheritClass( OO
.ui
.SearchInputWidget
, OO
.ui
.TextInputWidget
);
10238 OO
.ui
.SearchInputWidget
.prototype.getInputElement = function () {
10239 return $( '<input>' ).attr( 'type', 'search' );
10245 OO
.ui
.SearchInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
10246 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10247 // Clear the text field
10248 this.setValue( '' );
10255 * Update the 'clear' indicator displayed on type: 'search' text
10256 * fields, hiding it when the field is already empty or when it's not
10259 OO
.ui
.SearchInputWidget
.prototype.updateSearchIndicator = function () {
10260 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
10261 this.setIndicator( null );
10263 this.setIndicator( 'clear' );
10270 OO
.ui
.SearchInputWidget
.prototype.onChange = function () {
10271 OO
.ui
.SearchInputWidget
.parent
.prototype.onChange
.call( this );
10272 this.updateSearchIndicator();
10276 * Handle disable events.
10278 * @param {boolean} disabled Element is disabled
10281 OO
.ui
.SearchInputWidget
.prototype.onDisable = function () {
10282 this.updateSearchIndicator();
10288 OO
.ui
.SearchInputWidget
.prototype.setReadOnly = function ( state
) {
10289 OO
.ui
.SearchInputWidget
.parent
.prototype.setReadOnly
.call( this, state
);
10290 this.updateSearchIndicator();
10295 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
10296 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
10297 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
10299 * - by typing a value in the text input field. If the value exactly matches the value of a menu
10300 * option, that option will appear to be selected.
10301 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
10304 * After the user chooses an option, its `data` will be used as a new value for the widget.
10305 * A `label` also can be specified for each option: if given, it will be shown instead of the
10306 * `data` in the dropdown menu.
10308 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10310 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
10313 * // Example: A ComboBoxInputWidget.
10314 * var comboBox = new OO.ui.ComboBoxInputWidget( {
10315 * value: 'Option 1',
10317 * { data: 'Option 1' },
10318 * { data: 'Option 2' },
10319 * { data: 'Option 3' }
10322 * $( 'body' ).append( comboBox.$element );
10325 * // Example: A ComboBoxInputWidget with additional option labels.
10326 * var comboBox = new OO.ui.ComboBoxInputWidget( {
10327 * value: 'Option 1',
10330 * data: 'Option 1',
10331 * label: 'Option One'
10334 * data: 'Option 2',
10335 * label: 'Option Two'
10338 * data: 'Option 3',
10339 * label: 'Option Three'
10343 * $( 'body' ).append( comboBox.$element );
10345 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
10348 * @extends OO.ui.TextInputWidget
10351 * @param {Object} [config] Configuration options
10352 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
10353 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
10354 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
10355 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
10356 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
10357 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
10359 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
10360 // Configuration initialization
10361 config
= $.extend( {
10362 autocomplete
: false
10365 // ComboBoxInputWidget shouldn't support `multiline`
10366 config
.multiline
= false;
10368 // See InputWidget#reusePreInfuseDOM about `config.$input`
10369 if ( config
.$input
) {
10370 config
.$input
.removeAttr( 'list' );
10373 // Parent constructor
10374 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
10377 this.$overlay
= config
.$overlay
|| this.$element
;
10378 this.dropdownButton
= new OO
.ui
.ButtonWidget( {
10379 classes
: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
10381 disabled
: this.disabled
10383 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend(
10387 $floatableContainer
: this.$element
,
10388 disabled
: this.isDisabled()
10394 this.connect( this, {
10395 change
: 'onInputChange',
10396 enter
: 'onInputEnter'
10398 this.dropdownButton
.connect( this, {
10399 click
: 'onDropdownButtonClick'
10401 this.menu
.connect( this, {
10402 choose
: 'onMenuChoose',
10403 add
: 'onMenuItemsChange',
10404 remove
: 'onMenuItemsChange'
10408 this.$input
.attr( {
10410 'aria-owns': this.menu
.getElementId(),
10411 'aria-autocomplete': 'list'
10413 // Do not override options set via config.menu.items
10414 if ( config
.options
!== undefined ) {
10415 this.setOptions( config
.options
);
10417 this.$field
= $( '<div>' )
10418 .addClass( 'oo-ui-comboBoxInputWidget-field' )
10419 .append( this.$input
, this.dropdownButton
.$element
);
10421 .addClass( 'oo-ui-comboBoxInputWidget' )
10422 .append( this.$field
);
10423 this.$overlay
.append( this.menu
.$element
);
10424 this.onMenuItemsChange();
10429 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
10434 * Get the combobox's menu.
10436 * @return {OO.ui.MenuSelectWidget} Menu widget
10438 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
10443 * Get the combobox's text input widget.
10445 * @return {OO.ui.TextInputWidget} Text input widget
10447 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
10452 * Handle input change events.
10455 * @param {string} value New value
10457 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
10458 var match
= this.menu
.getItemFromData( value
);
10460 this.menu
.selectItem( match
);
10461 if ( this.menu
.getHighlightedItem() ) {
10462 this.menu
.highlightItem( match
);
10465 if ( !this.isDisabled() ) {
10466 this.menu
.toggle( true );
10471 * Handle input enter events.
10475 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
10476 if ( !this.isDisabled() ) {
10477 this.menu
.toggle( false );
10482 * Handle button click events.
10486 OO
.ui
.ComboBoxInputWidget
.prototype.onDropdownButtonClick = function () {
10487 this.menu
.toggle();
10492 * Handle menu choose events.
10495 * @param {OO.ui.OptionWidget} item Chosen item
10497 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
10498 this.setValue( item
.getData() );
10502 * Handle menu item change events.
10506 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
10507 var match
= this.menu
.getItemFromData( this.getValue() );
10508 this.menu
.selectItem( match
);
10509 if ( this.menu
.getHighlightedItem() ) {
10510 this.menu
.highlightItem( match
);
10512 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
10518 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
10520 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
10522 if ( this.dropdownButton
) {
10523 this.dropdownButton
.setDisabled( this.isDisabled() );
10526 this.menu
.setDisabled( this.isDisabled() );
10533 * Set the options available for this input.
10535 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10538 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
10541 .addItems( options
.map( function ( opt
) {
10542 return new OO
.ui
.MenuOptionWidget( {
10544 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
10552 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
10553 * which is a widget that is specified by reference before any optional configuration settings.
10555 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
10557 * - **left**: The label is placed before the field-widget and aligned with the left margin.
10558 * A left-alignment is used for forms with many fields.
10559 * - **right**: The label is placed before the field-widget and aligned to the right margin.
10560 * A right-alignment is used for long but familiar forms which users tab through,
10561 * verifying the current field with a quick glance at the label.
10562 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
10563 * that users fill out from top to bottom.
10564 * - **inline**: The label is placed after the field-widget and aligned to the left.
10565 * An inline-alignment is best used with checkboxes or radio buttons.
10567 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
10568 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
10570 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
10573 * @extends OO.ui.Layout
10574 * @mixins OO.ui.mixin.LabelElement
10575 * @mixins OO.ui.mixin.TitledElement
10578 * @param {OO.ui.Widget} fieldWidget Field widget
10579 * @param {Object} [config] Configuration options
10580 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
10581 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
10582 * The array may contain strings or OO.ui.HtmlSnippet instances.
10583 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
10584 * The array may contain strings or OO.ui.HtmlSnippet instances.
10585 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
10586 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
10587 * For important messages, you are advised to use `notices`, as they are always shown.
10588 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
10589 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
10591 * @throws {Error} An error is thrown if no widget is specified
10593 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
10594 // Allow passing positional parameters inside the config object
10595 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
10596 config
= fieldWidget
;
10597 fieldWidget
= config
.fieldWidget
;
10600 // Make sure we have required constructor arguments
10601 if ( fieldWidget
=== undefined ) {
10602 throw new Error( 'Widget not found' );
10605 // Configuration initialization
10606 config
= $.extend( { align
: 'left' }, config
);
10608 // Parent constructor
10609 OO
.ui
.FieldLayout
.parent
.call( this, config
);
10611 // Mixin constructors
10612 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, {
10613 $label
: $( '<label>' )
10615 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
10618 this.fieldWidget
= fieldWidget
;
10621 this.$field
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
10622 this.$messages
= $( '<ul>' );
10623 this.$header
= $( '<span>' );
10624 this.$body
= $( '<div>' );
10626 if ( config
.help
) {
10627 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
10628 $overlay
: config
.$overlay
,
10632 classes
: [ 'oo-ui-fieldLayout-help' ],
10636 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
10637 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
10639 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
10641 this.$help
= this.popupButtonWidget
.$element
;
10643 this.$help
= $( [] );
10647 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
10650 if ( this.fieldWidget
.getInputId() ) {
10651 this.$label
.attr( 'for', this.fieldWidget
.getInputId() );
10653 this.$label
.on( 'click', function () {
10654 this.fieldWidget
.focus();
10659 .addClass( 'oo-ui-fieldLayout' )
10660 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget
.isDisabled() )
10661 .append( this.$body
);
10662 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
10663 this.$header
.addClass( 'oo-ui-fieldLayout-header' );
10664 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
10666 .addClass( 'oo-ui-fieldLayout-field' )
10667 .append( this.fieldWidget
.$element
);
10669 this.setErrors( config
.errors
|| [] );
10670 this.setNotices( config
.notices
|| [] );
10671 this.setAlignment( config
.align
);
10676 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
10677 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
10678 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
10683 * Handle field disable events.
10686 * @param {boolean} value Field is disabled
10688 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
10689 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
10693 * Get the widget contained by the field.
10695 * @return {OO.ui.Widget} Field widget
10697 OO
.ui
.FieldLayout
.prototype.getField = function () {
10698 return this.fieldWidget
;
10702 * Return `true` if the given field widget can be used with `'inline'` alignment (see
10703 * #setAlignment). Return `false` if it can't or if this can't be determined.
10705 * @return {boolean}
10707 OO
.ui
.FieldLayout
.prototype.isFieldInline = function () {
10708 // This is very simplistic, but should be good enough.
10709 return this.getField().$element
.prop( 'tagName' ).toLowerCase() === 'span';
10714 * @param {string} kind 'error' or 'notice'
10715 * @param {string|OO.ui.HtmlSnippet} text
10718 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
10719 var $listItem
, $icon
, message
;
10720 $listItem
= $( '<li>' );
10721 if ( kind
=== 'error' ) {
10722 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
10723 } else if ( kind
=== 'notice' ) {
10724 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
10728 message
= new OO
.ui
.LabelWidget( { label
: text
} );
10730 .append( $icon
, message
.$element
)
10731 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
10736 * Set the field alignment mode.
10739 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
10742 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
10743 if ( value
!== this.align
) {
10744 // Default to 'left'
10745 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
10749 if ( value
=== 'inline' && !this.isFieldInline() ) {
10752 // Reorder elements
10753 if ( value
=== 'top' ) {
10754 this.$header
.append( this.$label
, this.$help
);
10755 this.$body
.append( this.$header
, this.$field
);
10756 } else if ( value
=== 'inline' ) {
10757 this.$header
.append( this.$label
, this.$help
);
10758 this.$body
.append( this.$field
, this.$header
);
10760 this.$header
.append( this.$label
);
10761 this.$body
.append( this.$header
, this.$help
, this.$field
);
10763 // Set classes. The following classes can be used here:
10764 // * oo-ui-fieldLayout-align-left
10765 // * oo-ui-fieldLayout-align-right
10766 // * oo-ui-fieldLayout-align-top
10767 // * oo-ui-fieldLayout-align-inline
10768 if ( this.align
) {
10769 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
10771 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
10772 this.align
= value
;
10779 * Set the list of error messages.
10781 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
10782 * The array may contain strings or OO.ui.HtmlSnippet instances.
10785 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
10786 this.errors
= errors
.slice();
10787 this.updateMessages();
10792 * Set the list of notice messages.
10794 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
10795 * The array may contain strings or OO.ui.HtmlSnippet instances.
10798 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
10799 this.notices
= notices
.slice();
10800 this.updateMessages();
10805 * Update the rendering of error and notice messages.
10809 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
10811 this.$messages
.empty();
10813 if ( this.errors
.length
|| this.notices
.length
) {
10814 this.$body
.after( this.$messages
);
10816 this.$messages
.remove();
10820 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
10821 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
10823 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
10824 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
10829 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
10830 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
10831 * is required and is specified before any optional configuration settings.
10833 * Labels can be aligned in one of four ways:
10835 * - **left**: The label is placed before the field-widget and aligned with the left margin.
10836 * A left-alignment is used for forms with many fields.
10837 * - **right**: The label is placed before the field-widget and aligned to the right margin.
10838 * A right-alignment is used for long but familiar forms which users tab through,
10839 * verifying the current field with a quick glance at the label.
10840 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
10841 * that users fill out from top to bottom.
10842 * - **inline**: The label is placed after the field-widget and aligned to the left.
10843 * An inline-alignment is best used with checkboxes or radio buttons.
10845 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
10846 * text is specified.
10849 * // Example of an ActionFieldLayout
10850 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
10851 * new OO.ui.TextInputWidget( {
10852 * placeholder: 'Field widget'
10854 * new OO.ui.ButtonWidget( {
10858 * label: 'An ActionFieldLayout. This label is aligned top',
10860 * help: 'This is help text'
10864 * $( 'body' ).append( actionFieldLayout.$element );
10867 * @extends OO.ui.FieldLayout
10870 * @param {OO.ui.Widget} fieldWidget Field widget
10871 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
10872 * @param {Object} config
10874 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
10875 // Allow passing positional parameters inside the config object
10876 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
10877 config
= fieldWidget
;
10878 fieldWidget
= config
.fieldWidget
;
10879 buttonWidget
= config
.buttonWidget
;
10882 // Parent constructor
10883 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
10886 this.buttonWidget
= buttonWidget
;
10887 this.$button
= $( '<span>' );
10888 this.$input
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
10892 .addClass( 'oo-ui-actionFieldLayout' );
10894 .addClass( 'oo-ui-actionFieldLayout-button' )
10895 .append( this.buttonWidget
.$element
);
10897 .addClass( 'oo-ui-actionFieldLayout-input' )
10898 .append( this.fieldWidget
.$element
);
10900 .append( this.$input
, this.$button
);
10905 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
10908 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
10909 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
10910 * configured with a label as well. For more information and examples,
10911 * please see the [OOjs UI documentation on MediaWiki][1].
10914 * // Example of a fieldset layout
10915 * var input1 = new OO.ui.TextInputWidget( {
10916 * placeholder: 'A text input field'
10919 * var input2 = new OO.ui.TextInputWidget( {
10920 * placeholder: 'A text input field'
10923 * var fieldset = new OO.ui.FieldsetLayout( {
10924 * label: 'Example of a fieldset layout'
10927 * fieldset.addItems( [
10928 * new OO.ui.FieldLayout( input1, {
10929 * label: 'Field One'
10931 * new OO.ui.FieldLayout( input2, {
10932 * label: 'Field Two'
10935 * $( 'body' ).append( fieldset.$element );
10937 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
10940 * @extends OO.ui.Layout
10941 * @mixins OO.ui.mixin.IconElement
10942 * @mixins OO.ui.mixin.LabelElement
10943 * @mixins OO.ui.mixin.GroupElement
10946 * @param {Object} [config] Configuration options
10947 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
10948 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
10949 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
10950 * For important messages, you are advised to use `notices`, as they are always shown.
10951 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
10952 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
10954 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
10955 // Configuration initialization
10956 config
= config
|| {};
10958 // Parent constructor
10959 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
10961 // Mixin constructors
10962 OO
.ui
.mixin
.IconElement
.call( this, config
);
10963 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: $( '<div>' ) } ) );
10964 OO
.ui
.mixin
.GroupElement
.call( this, config
);
10967 this.$header
= $( '<div>' );
10968 if ( config
.help
) {
10969 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
10970 $overlay
: config
.$overlay
,
10974 classes
: [ 'oo-ui-fieldsetLayout-help' ],
10978 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
10979 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
10981 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
10983 this.$help
= this.popupButtonWidget
.$element
;
10985 this.$help
= $( [] );
10990 .addClass( 'oo-ui-fieldsetLayout-header' )
10991 .append( this.$icon
, this.$label
, this.$help
);
10992 this.$group
.addClass( 'oo-ui-fieldsetLayout-group' );
10994 .addClass( 'oo-ui-fieldsetLayout' )
10995 .prepend( this.$header
, this.$group
);
10996 if ( Array
.isArray( config
.items
) ) {
10997 this.addItems( config
.items
);
11003 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
11004 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
11005 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
11006 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
11008 /* Static Properties */
11014 OO
.ui
.FieldsetLayout
.static.tagName
= 'fieldset';
11017 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
11018 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
11019 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
11020 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11022 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
11023 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
11024 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
11025 * some fancier controls. Some controls have both regular and InputWidget variants, for example
11026 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
11027 * often have simplified APIs to match the capabilities of HTML forms.
11028 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
11030 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
11031 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11034 * // Example of a form layout that wraps a fieldset layout
11035 * var input1 = new OO.ui.TextInputWidget( {
11036 * placeholder: 'Username'
11038 * var input2 = new OO.ui.TextInputWidget( {
11039 * placeholder: 'Password',
11042 * var submit = new OO.ui.ButtonInputWidget( {
11046 * var fieldset = new OO.ui.FieldsetLayout( {
11047 * label: 'A form layout'
11049 * fieldset.addItems( [
11050 * new OO.ui.FieldLayout( input1, {
11051 * label: 'Username',
11054 * new OO.ui.FieldLayout( input2, {
11055 * label: 'Password',
11058 * new OO.ui.FieldLayout( submit )
11060 * var form = new OO.ui.FormLayout( {
11061 * items: [ fieldset ],
11062 * action: '/api/formhandler',
11065 * $( 'body' ).append( form.$element );
11068 * @extends OO.ui.Layout
11069 * @mixins OO.ui.mixin.GroupElement
11072 * @param {Object} [config] Configuration options
11073 * @cfg {string} [method] HTML form `method` attribute
11074 * @cfg {string} [action] HTML form `action` attribute
11075 * @cfg {string} [enctype] HTML form `enctype` attribute
11076 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
11078 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
11081 // Configuration initialization
11082 config
= config
|| {};
11084 // Parent constructor
11085 OO
.ui
.FormLayout
.parent
.call( this, config
);
11087 // Mixin constructors
11088 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11091 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
11093 // Make sure the action is safe
11094 action
= config
.action
;
11095 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
11096 action
= './' + action
;
11101 .addClass( 'oo-ui-formLayout' )
11103 method
: config
.method
,
11105 enctype
: config
.enctype
11107 if ( Array
.isArray( config
.items
) ) {
11108 this.addItems( config
.items
);
11114 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
11115 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
11120 * A 'submit' event is emitted when the form is submitted.
11125 /* Static Properties */
11131 OO
.ui
.FormLayout
.static.tagName
= 'form';
11136 * Handle form submit events.
11139 * @param {jQuery.Event} e Submit event
11142 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
11143 if ( this.emit( 'submit' ) ) {
11149 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
11150 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
11153 * // Example of a panel layout
11154 * var panel = new OO.ui.PanelLayout( {
11158 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
11160 * $( 'body' ).append( panel.$element );
11163 * @extends OO.ui.Layout
11166 * @param {Object} [config] Configuration options
11167 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
11168 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
11169 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
11170 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
11172 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
11173 // Configuration initialization
11174 config
= $.extend( {
11181 // Parent constructor
11182 OO
.ui
.PanelLayout
.parent
.call( this, config
);
11185 this.$element
.addClass( 'oo-ui-panelLayout' );
11186 if ( config
.scrollable
) {
11187 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
11189 if ( config
.padded
) {
11190 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
11192 if ( config
.expanded
) {
11193 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
11195 if ( config
.framed
) {
11196 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
11202 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
11207 * Focus the panel layout
11209 * The default implementation just focuses the first focusable element in the panel
11211 OO
.ui
.PanelLayout
.prototype.focus = function () {
11212 OO
.ui
.findFocusable( this.$element
).focus();
11216 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11217 * items), with small margins between them. Convenient when you need to put a number of block-level
11218 * widgets on a single line next to each other.
11220 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11223 * // HorizontalLayout with a text input and a label
11224 * var layout = new OO.ui.HorizontalLayout( {
11226 * new OO.ui.LabelWidget( { label: 'Label' } ),
11227 * new OO.ui.TextInputWidget( { value: 'Text' } )
11230 * $( 'body' ).append( layout.$element );
11233 * @extends OO.ui.Layout
11234 * @mixins OO.ui.mixin.GroupElement
11237 * @param {Object} [config] Configuration options
11238 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11240 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
11241 // Configuration initialization
11242 config
= config
|| {};
11244 // Parent constructor
11245 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
11247 // Mixin constructors
11248 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11251 this.$element
.addClass( 'oo-ui-horizontalLayout' );
11252 if ( Array
.isArray( config
.items
) ) {
11253 this.addItems( config
.items
);
11259 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
11260 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
11264 //# sourceMappingURL=oojs-ui-core.js.map